﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Diagnostics;
using System.Reflection;


#region 联机功能命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;
#endregion
namespace siguo_shrx.server
{
    public partial class Mainfrm : Form
    {
        #region 标志功能区
        static public Mainfrm Instance;
        static public string VERSION;

        //public int[,] buju=new int[5,30];
        private RadioButton[] rd_btns;//单选框数组
        private BJInfo[] buju = new BJInfo[7]; //布局存放，最多同时存放6组，0为只布局调入1-4为复盘调入红、蓝、绿、紫，5为自己布局，6为联机对家布局。
        private short playerFlag;//标记方向标识
        //private int[,] qipan = new int[17, 17];//调入布局标记时用到有棋盘结构
        //private bool GameFlag;//标记游戏窗口是否开启
        private static bool JunqiRpgFlag;//军棋窗体标识
        //private bool wating = true;//载入军棋窗体标识。
        public static short mysitColor;//自己当前座位的颜色。
        private short mysitColorTemp;//上次当前座位的颜色存放
        bool mysitColorChanged=false;//是否换位置了。
        //int waitColor;//行棋等待执行座位颜色
        bool createIndexFlag = false;//创建索引标识

        private short[] piece = { 30, 30, 30, 30 };//子力计算
        private short[] maxpiece = { 5, 5, 5, 5 };//最大子力
        private short[] cmdOperaed = new short[10]; //存放上一条执行完毕的指令 （5F）（指令位：% 4）（起始位y1）（起始位x1）（起始位y2）（起始位x2）


        ChessboardInfo[,] ActChessboard = new ChessboardInfo[17, 17];//自动标记时用到的棋盘结构。
        bool Auto = false;//自动标记开始标志


        //IntPtr hwndQQGame;//QQGame游戏窗口句柄
        private IntPtr hwndJunqiRpg;//军棋游戏窗口句柄
        IntPtr hwndJunqiRpgOpened;//军棋游戏窗口句柄
        IntPtr JunQiRpgAddressPointer = (IntPtr)0x4B5F34;//0x4B5C98;//x4C8E51;//棋盘起始地址004B5C98 第一个位置从0开始
        IntPtr SitColorAddressPointet = (IntPtr)0x4B4CBC;//0x4B4A24;//当前座位颜色地址 红0 蓝1 绿2 紫3
        IntPtr InstructionAddressPointer = (IntPtr)0x4B8480;//0x4B81E8;//动作指令地址
        IntPtr InstructionFlagAddressPointer = (IntPtr)0x4B84C4;//0x4B822C;//动作执行状态标记地址：004B822C，值0为已经执行，值1为正在执行。
        IntPtr MyselfLayoutAddressPointer = (IntPtr)0x4B4CC0;//0x4B4A28;//自己的布局起始地址。

        IntPtr BeginAddressPointer =(IntPtr)0x0;//开始按钮位置

        IntPtr StepAddressPointet = (IntPtr)0x4B4D00;//0x4B4A68;//0x4C7C30;//步数地址004C6B28
        uint step = 0;//步数
        //bool ChessChange = false;//棋子是否发生了变化。


        uint[] JunQiRpgQiZiAddress = new uint[1];//读写内存地址
        uint[] QiZiWrite = new uint[1]; //准备写入内存 数据
        uint[] QiZiRead = new uint[1];  //用来存放当前内存数据

        short FULLBIT = 0xF;//一个棋子占多少位
        short MARKBIT = 0x8;//标记位位于第几位
        short UNMODIFYBIT = 0x0;//实际棋子大小位于第几位
        short COLORBIT = 0x4;//棋子颜色位于第几位

        const short ROWS = 0x10;//十七个列，从0开始
        const int ROWS_AND_COLS = 0x110;//十七个行，从0开始

        string fupanFullPath = "";
        FileSystemWatcher fileWatcher = new FileSystemWatcher(Application.StartupPath);//监视应用程序当程目录下的文件变化

        public Mainfrm()
        {
            InitializeComponent();           

            #region 版本信息
            Instance = this;
            AssemblyName aName = this.GetType().Assembly.GetName();
            Version v = aName.Version;
            //int rev = Convert.ToInt32(svnid.Split(' ')[1]);
            DateTime CompileTime = GetPe32Time(this.GetType().Assembly.Location);
            if (CompileTime == DateTime.MinValue)
                CompileTime = File.GetLastWriteTime(this.GetType().Assembly.Location);
            VERSION = Text = string.Format("四国双人行(Server) {0} [{1} 测试版本](511576392@qq.com)", v, CompileTime.ToString("yyyy-MM-dd"));
            Instance.Text = VERSION;
            notifyIcon1.Text = VERSION;
            #endregion

            for (int i = 0; i < 7; i++)
            {
                buju[i] = new BJInfo();//使用前先实例化变量
            }

            rd_btns = new RadioButton[5];
            rd_btns[0] = this.radioButton5;
            rd_btns[1] = this.radioButton1;
            rd_btns[2] = this.radioButton2;
            rd_btns[3] = this.radioButton3;
            rd_btns[4] = this.radioButton4;

            for (int i = 0; i < 17; i++)//实例化棋盘结构
            {
                for (int j = 0; j < 17; j++)
                {
                    ActChessboard[i, j] = new ChessboardInfo();
                }
            }

            fileWatcher.Created += new FileSystemEventHandler(OnChanged);//事件以方法关联
            fileWatcher.EnableRaisingEvents = true;//激活事件
        }

        private void cmbVersion_SelectedIndexChanged(object sender, EventArgs e)
        {
            OnVersionChanged();
        }

        /// <summary>
        /// 选择游戏版本
        /// </summary>
        private void OnVersionChanged()
        {
            //MessageBox.Show("sfs");
            switch (cmbVersion.SelectedIndex)
            {
                case 0://四国军棋版本信息：四国军棋角色版 2.1 Beta08 Build011
                    JunQiRpgAddressPointer = (IntPtr)0x4B5F34;//0x4B5C98;//x4C8E51;//棋盘起始地址004B5C98 第一个位置从0开始
                    SitColorAddressPointet = (IntPtr)0x4B4CBC;//0x4B4A24;//当前座位颜色地址 红0 蓝1 绿2 紫3
                    InstructionAddressPointer = (IntPtr)0x4B8480;//0x4B81E8;//动作指令地址
                    InstructionFlagAddressPointer = (IntPtr)0x4B84C4;//0x4B822C;//动作执行状态标记地址：004B822C，值0为已经执行，值1为正在执行。
                    MyselfLayoutAddressPointer = (IntPtr)0x4B4CC0;//0x4B4A28;//自己的布局起始地址。
                    StepAddressPointet = (IntPtr)0x4B4D00;//0x4B4A68;//0x4C7C30;//步数地址004C6B28

                    FULLBIT = 0xF;//一个棋子占多少位
                    MARKBIT = 0x8;//标记位位于第几位
                    UNMODIFYBIT = 0x0;//实际棋子大小位于第几位
                    COLORBIT = 0x4;//棋子颜色位于第几位

                    BeginAddressPointer =(IntPtr)0x0;//开始按钮位置
                    break;
                case 1://四国军棋版本信息：四国军棋角色版 2.1 Beta08 Build021
                    JunQiRpgAddressPointer = (IntPtr)0x4BA294;//棋盘起始地址004B5C98 第一个位置从0开始
                    SitColorAddressPointet = (IntPtr)0x4B901C;//当前座位颜色地址 红0 蓝1 绿2 紫3
                    MyselfLayoutAddressPointer = (IntPtr)0x4B9020;//0x4B4A28;//自己的布局起始地址。
                    InstructionAddressPointer = (IntPtr)0x4BC7E0;//0x4B81E8;//动作指令地址
                    InstructionFlagAddressPointer = (IntPtr)0x4BC824;//动作执行状态标记地址：004B822C，值0为已经执行，值1为正在执行。
                    
                    StepAddressPointet = (IntPtr)0x4B9060;//步数地址004C6B28

                    FULLBIT = 0xF;//一个棋子占多少位
                    MARKBIT = 0x8;//标记位位于第几位
                    UNMODIFYBIT = 0x0;//实际棋子大小位于第几位
                    COLORBIT = 0x4;//棋子颜色位于第几位

                    BeginAddressPointer =(IntPtr)0x0;//开始按钮位置
                    break;
                case 2://四国军棋版本信息：四国军棋角色版 2.1 Beta08 Build024
                    JunQiRpgAddressPointer = (IntPtr)0x004BB354;//4BA294棋盘起始地址004B5C98 第一个位置从0开始
                    SitColorAddressPointet = (IntPtr)0x4BA0DC;//4B901C当前座位颜色地址 红0 蓝1 绿2 紫3
                    MyselfLayoutAddressPointer = (IntPtr)0x4BA0E0;//4B9020;0x4B4A28;//自己的布局起始地址。
                    InstructionAddressPointer = (IntPtr)0x004BD8A0;//4BC7E0;0x4B81E8;//动作指令地址
                    InstructionFlagAddressPointer = (IntPtr)0x004BD8E4;//4BC824动作执行状态标记地址：004B822C，值0为已经执行，值1为正在执行。
                    
                    StepAddressPointet = (IntPtr)0x004BA120;//4B9060步数地址004C6B28

                    FULLBIT = 0xF;//一个棋子占多少位
                    MARKBIT = 0x8;//标记位位于第几位
                    UNMODIFYBIT = 0x0;//实际棋子大小位于第几位
                    COLORBIT = 0x4;//棋子颜色位于第几位
                    //QQ号位置：004BA0D0，如511576392 （1E7E 0948）：48 09 7E 1E
                    //窗口活动标志位：004C05D4
                    //四个按钮位（00487230、00487290、004872F0、00487350）存在为1.空为0
                    BeginAddressPointer = (IntPtr)0x00487230;
                    break;
                case 3://四国军棋版本信息：四国军棋角色版 2.1 Beta08 Build026
                    JunQiRpgAddressPointer = (IntPtr)0x0049DD1C;//0x004BB354;//4BA294棋盘起始地址004B5C98 第一个位置从0开始
                    SitColorAddressPointet = (IntPtr)0x0049CAA4;//0x4BA0DC;//4B901C当前座位颜色地址 红0 蓝1 绿2 紫3
                    MyselfLayoutAddressPointer = (IntPtr)0x0049CAA8;//0x4BA0E0;//4B9020;0x4B4A28;//自己的布局起始地址。
                    InstructionAddressPointer = (IntPtr)0x004A0268;//0x004BD8A0;//4BC7E0;0x4B81E8;//动作指令地址
                    InstructionFlagAddressPointer = (IntPtr)0x004A02AC;//0x004BD8E4;//4BC824动作执行状态标记地址：004B822C，值0为已经执行，值1为正在执行。
                    
                    StepAddressPointet = (IntPtr)0x0049CAE8;//0x004BA120;//4B9060步数地址004C6B28

                    FULLBIT = 0xF;//一个棋子占多少位
                    MARKBIT = 0x8;//标记位位于第几位
                    UNMODIFYBIT = 0x0;//实际棋子大小位于第几位
                    COLORBIT = 0x4;//棋子颜色位于第几位
                    //QQ号位置：004C8448，如511576392 （1E7E 0948）：48 09 7E 1E
                    //窗口活动标志位：004A2F7C
                    //四个按钮位（00469BF8、00469C58、00469CB8、00469D18）存在为1.空为0
                    BeginAddressPointer = (IntPtr)0x00469BF8;
                    break;
                default:
                    break;
            }
        }

        delegate void OnChangedDelegate(object source, FileSystemEventArgs e);


        //文件发生了变化
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            
            if (this.btn_Open.InvokeRequired)//等待异步
            {
                OnChangedDelegate onchangedelegate = new OnChangedDelegate(OnChanged);
                this.Invoke(onchangedelegate,source,e);//通过代理调用刷新方法
            }
            else
            {
                WatcherChangeTypes changeType = e.ChangeType;
                if (e.FullPath.Substring(e.FullPath.Length - 3, 3).Equals("jgs"))
                {
                    fupanFullPath = e.FullPath;
                    LoadingFupan(fupanFullPath);
                    btn_Open.Enabled = true;
                }
                
            }
        }

        //打开复盘
        private void btn_Open_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(fupanFullPath); //打开复盘
        }

        //调入复盘数据
        private void btn_FuPan_Click(object sender, EventArgs e)
        {

            switch (openFileDialog2.ShowDialog())
            {
                case DialogResult.Yes:
                case DialogResult.OK:
                    break;
                default:
                    return;
            }
            LoadingFupan(openFileDialog2.FileName);
        }

        //调入布局数据
        private void btn_BuJu_Click(object sender, EventArgs e)
        {
            LoadingBuju();
        }

        /// <summary>
        /// 选择或取消自动标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkAutoBJ_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAutoBJ.Checked == true)
            {
                Star();
            }
            else
            {
                Stop();
            }
        }

        /// <summary>
        /// 侦听四国军棋游戏窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_findGame_Tick(object sender, EventArgs e)
        {
            //hwndQQGame = ProcessApi.FindWindow("QufPanelWnd", "QQ游戏");

            #region 查找四国军棋游戏窗口
            StringBuilder title = new StringBuilder(512);
            if (hwndJunqiRpg == (IntPtr)0)
            {
                if (Auto == true)
                {
                    Stop();//当游戏窗口关闭，自动标志停止
                }

                btn_Up.Enabled = false;
                btn_Left.Enabled = false;
                btn_Right.Enabled = false;
                btn_Cls.Enabled = false;
                chkAutoBJ.Enabled = false;
                btn_Blue.Enabled = false;
                btn_Green.Enabled = false;
                btn_Red.Enabled = false;
                btn_Purple.Enabled = false;
                btnMySelf.Enabled = false;

                label3.Text = "等待载入四国游戏窗体...";
                label3.ForeColor = Color.Red;

                //查找四国游戏窗口句柄
                FindJunQiRpgHwnd();

            }
            else
            {
                ProcessApi.GetWindowText((int)hwndJunqiRpg, title, title.Capacity);
                if (Convert.ToString(title) == "四国军棋角色版")
                {
                    btn_Up.Enabled = true;
                    btn_Left.Enabled = true;
                    btn_Right.Enabled = true;
                    btn_Cls.Enabled = true;
                    //btn_ZhiNeng.Enabled = true;
                    chkAutoBJ.Enabled = true;
                    btnMySelf.Enabled = true;

                    ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, SitColorAddressPointet, QiZiRead, 1, (IntPtr)0);
                    mysitColor = Convert.ToInt16(QiZiRead[0]);

                    if (mysitColor!=mysitColorTemp)//与上次颜色不一样，换位了。
                    {
                        mysitColorTemp = mysitColor;
                        mysitColorChanged = true;

                        switch (mysitColor)//禁止对自己进行标记
                        {
                            case 0:
                                btn_Blue.Enabled = true;
                                btn_Green.Enabled = true;
                                btn_Red.Enabled = false;
                                btn_Purple.Enabled = true;
                                break;
                            case 1:
                                btn_Blue.Enabled = false;
                                btn_Green.Enabled = true;
                                btn_Red.Enabled = true;
                                btn_Purple.Enabled = true;
                                break;
                            case 2:
                                btn_Blue.Enabled = true;
                                btn_Green.Enabled = false;
                                btn_Red.Enabled = true;
                                btn_Purple.Enabled = true;
                                break;
                            case 3:
                                btn_Blue.Enabled = true;
                                btn_Green.Enabled = true;
                                btn_Red.Enabled = true;
                                btn_Purple.Enabled = false;
                                break;
                        }

                        Initializtion();//初始化棋盘
 
                    }



                    

                    #region 联机信息交换
                    if (Connected == true)
                    {
                        //发送模块
                        if (step == 0)
                        {
                            if (mysitColor != buju[5].Color || MySelfLayoutChange() || SendTime == 0)
                            {
                                //更新自己布局
                                ReadMyselfLayoutInfo();
                                SendBujuInfo(buju[5]);//发送布局
                                MyselfLayoutChangeFlag = false;
                                SendTime++;
                            }
                        }
                        else
                        {
                            if (MyselfLayoutChangeFlag == true)
                            {
                                SendBujuInfo(buju[5]);//发送布局
                                MyselfLayoutChangeFlag = false;
                                SendTime++;
                            }
                        }
                        //标记模块
                        if (ArriveFlag == true)
                        {
                            ArriveConvertBuJuInfo(MarkMsg);
                            ArriveFlag = false;
                        }
                    }
                    #endregion

                    #region 记牌信息重置
                    if (step == 0)
                    {
                        if (mysitColorChanged||ReSetTime == 0)//换位置了，跟下完一局后
                        {
                            monitorCtrl.ReSet(this, e);//重画记牌区
                            ReSetTime++;
                            mysitColorChanged = false;
                        }
                    }

                    #endregion

                }
                else
                {
                    hwndJunqiRpg = (IntPtr)0;
                    JunqiRpgFlag = false;
                }
                    
            }
            #endregion

        }

        /// <summary>
        /// 布局发生了改变
        /// </summary>
        /// <returns></returns>
        private bool MySelfLayoutChange()
        {
            short[] temp = MySelfLayout();
            for (int i = 0; i < 30; i++)
            {
                if (temp[i] != buju[5].BuJuInfo[i])
                {
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// 读取自己的布局信息
        /// </summary>
        private void ReadMyselfLayoutInfo()
        {
            short[] bujuinfo = MySelfLayout();
            buju[5].BuJuInfo = bujuinfo;
            buju[5].Color = mysitColor;
            //WriteBJtest();
        }

        /// <summary>
        /// 返回自己的布局信息
        /// </summary>
        /// <returns></returns>
        private short[] MySelfLayout()
        {
            short[] bujuinfo = new short[30];
            for (int i = 0; i < 30; i++)
            {
                ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)MyselfLayoutAddressPointer + i), QiZiRead, 1, (IntPtr)0);
                bujuinfo[i] = (short)QiZiRead[0];
            }
            return bujuinfo;
        }

        /// <summary>
        /// 载入选中的布局，对红方进行标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Red_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag = 0;
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                SelectBJ();
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }

        /// <summary>
        /// 载入选中的布局，对绿方进行标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Green_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag = 2;
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                SelectBJ();
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }
        
        /// <summary>
        /// 载入选中的布局，对蓝方进行标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Blue_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag = 1;
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                SelectBJ();
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }

        /// <summary>
        /// 载入选中的布局，对紫方进行标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Purple_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag = 3;
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                SelectBJ();
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }

        /// <summary>
        /// 载入选中的布局，对 左家 进行标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Left_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag =Convert.ToInt16((mysitColor + 1) % 4);
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                SelectBJ();
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }

        /// <summary>
        /// 载入选中的布局，对 对家 进行标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Up_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag =Convert.ToInt16((mysitColor + 2) % 4);
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                SelectBJ();
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }

        /// <summary>
        /// 载入选中的布局，对 右家 进行标记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Right_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag = Convert.ToInt16((mysitColor + 3) % 4);
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                SelectBJ();
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }

        /// <summary>
        /// 撤消所有标记信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cls_Click(object sender, EventArgs e)
        {
            BJ_Cls();
        }

        /// <summary>
        /// 对自己调入布局
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMySelf_Click(object sender, EventArgs e)
        {
            if (buju[0].FileName != null || buju[1].FileName != null)
            {
                playerFlag = -1;
                btn_Ok.Enabled = true;
                btn_Cancel.Enabled = true;
                label3.Text = "将对 自己　调入布局……";
            }
            else
            {
                MessageBox.Show("请先调入布局或复盘！");
            }
        }

        /// <summary>
        /// 处理调入复盘数据
        /// </summary>
        private void LoadingFupan(string strFileInfo)
        {
            //复盘数据结构为：40字节 头文件信息
            //四个玩家信息，每个玩家88字节。共计392字节。
            //=====================
            //20字节 玩家名字
            //30字节 布局信息
            //2字节 保留字段：为00
            //4字节 QQ号  保存方式为：将QQ号转换成16进制，得到8位16进制数，从低位开始，每二位数用一个字节表示 如：511576392→0X1E7E0948→48 09 7E 1E
            //20字节 保留字段
            //4字节 其它信息
            //1字节 顺序为 1 2 3 0    （颜色表示则为：0为红 1为蓝 2为绿 3为紫）
            //7字节 保留字段：全留空
            //=====================
            //20字节 保留字段：全留空
            //指令 每条指令10字节。
            //8字节 结束标志：全留空

            byte[] buffer = new byte[392];
            for (int i = 1; i < 5; i++)
            {
                buju[i].BuJuInfo = null;
                buju[i].User = "";
                buju[i].QQInfo = 0;
            }

            FileStream fileStream = 
                new FileStream(strFileInfo, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//设置文件共享方式为读写，FileShare.ReadWrite，这样的话，就可以打开了

            fileStream.Read(buffer, 0, buffer.Length);
            int id = strFileInfo.LastIndexOf("\\");
            string FileName = strFileInfo.Substring(id + 1, strFileInfo.Length - id - 5);//截取文件名

            for (int i = 1; i < 5; i++)
            {
                buju[i].FileName = FileName;
            }
            fileStream.Close();

            int begin = 40;
            for (int i = 1; i < 5; i++)
            {
                short[] bujuinfo = new short[30];
                //处理用户名
                byte[] userArr = new byte[20];
                for (int j = begin; j < begin + 20; j++)
                {
                    userArr[j - begin] = buffer[j];
                }
                string str = System.Text.Encoding.GetEncoding("GB2312").GetString(userArr, 0, 20);//处理问题的利器！！

                if (str != "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
                {
                    buju[i].User = str;
                }

                //处理布局数据
                for (int j = begin + 20; j < begin + 50; j++)
                {
                    bujuinfo[j - begin - 20] = Convert.ToInt16(buffer[j]);
                }
                buju[i].BuJuInfo = bujuinfo;

                //处理QQ号码
                for (int j = 0; j < 4; j++)
                {
                    buju[i].QQInfo += (int)(buffer[begin + 52 + j] % 16 * Math.Pow(16, 2 * j) + buffer[begin + 52 + j] / 16 * Math.Pow(16, 2 * j + 1));
                }

                buju[i].Color = Convert.ToInt16(buffer[begin + 80]);//处理颜色数据
                begin += 88;
                //labe.l1.Text += buju[1, i - 20]+" ";
            }
            ShowBuJuInfo();

        }

        /// <summary>
        /// 处理调入布局数据
        /// </summary>
        private void LoadingBuju()
        {
            short[] bujuinfo = new short[30];
            byte[] buffer = new byte[50];
            switch (openFileDialog1.ShowDialog())
            {
                case DialogResult.Yes:
                case DialogResult.OK:
                    break;
                default:
                    return;
            }
            FileStream fileStream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
            fileStream.Read(buffer, 0, buffer.Length);

            int id = openFileDialog1.FileName.LastIndexOf("\\");
            buju[0].FileName = openFileDialog1.FileName.Substring(id + 1, openFileDialog1.FileName.Length - id - 5);//截取文件名
            buju[0].User = buju[0].FileName;
            fileStream.Close();
            for (int i = 20; i < 50; i++)
            {
                bujuinfo[i - 20] =Convert.ToInt16(buffer[i]);
                //label1.Text += buffer[i] + " ";
            }
            buju[0].BuJuInfo = bujuinfo;
            ShowBuJuInfo();
        }

        /// <summary>
        /// 显示选择标记信息
        /// </summary>
        private void SelectBJ()
        {

            //ShowBuJuInfo();
            switch (playerFlag)
            {
                case 0:
                    label3.Text = "将对 红 方进行标记……";
                    rd_btns[1].Checked = true;
                    break;
                case 1:
                    label3.Text = "将对 蓝 方进行标记……";
                    rd_btns[2].Checked = true;
                    break;
                case 2:
                    label3.Text = "将对 绿 方进行标记……";
                    rd_btns[3].Checked = true;
                    break;
                case 3:
                    label3.Text = "将对 紫 方进行标记……";
                    rd_btns[4].Checked = true;
                    break;
            }
        }

        /// <summary>
        /// 显示布局信息
        /// </summary>
        private void ShowBuJuInfo()
        {
            for (int i = 0; i < 5; i++)
            {
                if (buju[i].FileName != null)
                {
                    if (buju[i].User != "")
                    {
                        rdOpera(i);
                    }
                }
            }
        }

        private delegate void BiaojiHander(int i);
        /// <summary>
        /// 对单选框进行操作
        /// </summary>
        /// <param name="i"></param>
        private void rdOpera(int i)
        {
            if (rd_btns[i].InvokeRequired)//等待异步
            {
                BiaojiHander rdopera = new BiaojiHander(rdOpera);
                this.Invoke(rdopera, i);//通过代理调用刷新方法

            }
            else
            {
                rd_btns[i].Enabled = true;
                rd_btns[i].Text = buju[i].User + " " + buju[i].QQInfo;
            }
        }

        /// <summary>
        /// 确定标记操作，将布局信息写入游戏内存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Ok_Click(object sender, EventArgs e)
        {
            int i = 0;
            bool access = false;
            do
            {
                if (rd_btns[i].Checked == true)
                {
                    if (JunqiRpgFlag == true)
                    {
                        if (playerFlag != -1)//标记其他三方棋子
                        {
                            if (step == 0)//高效！
                            {
                                BJ_buju(checkBox1.Checked, playerFlag, buju[i].BuJuInfo);
                            }
                            else//智能！
                            {
                                StarMark(checkBox1.Checked, playerFlag, buju[i].BuJuInfo); 
                            }
                        }
                        else//对自己进行布局调入
                        {
                            ChangeMyselfBuju(buju[i].BuJuInfo);//写入布局数据
                            StarMark(true, mysitColor, buju[i].BuJuInfo);//根据数据在棋盘上显示
                        }
                    }
                    else
                    {
                        MessageBox.Show("四国游戏窗体已经退出，无法进行标记。");
                    }
                    access = true;
                }
                i++;
            } while (access != true && i < 5);
            btn_Cancel_Click(sender,e);
        }

        /// <summary>
        /// 调入布局
        /// </summary>
        private void ChangeMyselfBuju(short[] BujuInfo)
        {
            for (int i = 0; i < 30; i++)
            {
                QiZiWrite[0] = (uint)BujuInfo[i];
                ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)MyselfLayoutAddressPointer + i), QiZiWrite, 1, (IntPtr)0);
            }
        }

        /// <summary>
        /// 取消选择操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            btn_Ok.Enabled = false;
            btn_Cancel.Enabled = false;
        }

        /// <summary>
        /// 将选中布局写入游戏中,适用于棋子没有走动前，走动后用StarMark进行标记
        /// </summary>
        /// <param name="flag">以标记写入为false,以翻牌写入为true</param>
        /// <param name="playerFlag">要标记的玩家颜色编号（0、1、2、3）</param>
        /// <param name="BujuInfo">布局信息</param>
        private void BJ_buju(bool flag, int playerFlag, short[] BujuInfo)
        {
            if (flag == true)
            {
                switch (playerFlag)
                {
                    case 3:
                        //紫
                        //int x = 5;
                        //int y = 10;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];
                                ActChessboard[5 - i, 10 - j].Qizi = BujuInfo[5 * i + j];
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (5 - i) * ROWS_AND_COLS + (10 - j) * ROWS + UNMODIFYBIT), QiZiWrite, 1, (IntPtr)0);
                                WritePieceUnmodify(5 - i, 10 - j, BujuInfo[5 * i + j]);
                            }
                        }
                        break;

                    case 0:
                        //红
                        //int x = 10;
                        //int y = 11;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];
                                ActChessboard[10 - j, 11 + i].Qizi = BujuInfo[5 * i + j];
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (10 - j) * ROWS_AND_COLS + (11 + i) * ROWS + UNMODIFYBIT), QiZiWrite, 1, (IntPtr)0);
                                WritePieceUnmodify(10 - j, 11 + i, BujuInfo[5 * i + j]);
                            }
                        }
                        break;
                    case 1:
                        //蓝
                        //int x = 11;
                        //int y = 6;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];
                                ActChessboard[11 + i, 6 + j].Qizi = BujuInfo[5 * i + j];
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (11 + i) * ROWS_AND_COLS + (6 + j) * ROWS + UNMODIFYBIT), QiZiWrite, 1, (IntPtr)0);
                                WritePieceUnmodify(11 + i, 6 + j, BujuInfo[5 * i + j]);
                            }
                        }
                        break;
                    case 2:
                        //绿
                        //int x = 6;
                        //int y = 5;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];
                                ActChessboard[6 + j, 5 - i].Qizi = BujuInfo[5 * i + j];
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (6 + j) * ROWS_AND_COLS + (5 - i) * ROWS + UNMODIFYBIT), QiZiWrite, 1, (IntPtr)0);
                                WritePieceUnmodify(6 + j, 5 - i, BujuInfo[5 * i + j]);
                            }
                        }
                        break;


                }
            }
            else
            {
                switch (playerFlag)
                {
                    case 3:
                        //紫
                        //int x = 5;
                        //int y = 10;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];                                
                                //ActChessboard[5 - i, 10 - j].Qizi = (int)QiZiWrite[0];
                                ActChessboard[5 - i, 10 - j].Qizi = BujuInfo[5 * i + j];
                                //QiZitoBJ(QiZiWrite);
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (5 - i) * ROWS_AND_COLS + (10 - j) * ROWS + MARKBIT), QiZiWrite, 1, (IntPtr)0);
                                WritePiece(5 - i, 10 - j, BujuInfo[5 * i + j]);
                            }
                        }
                        break;

                    case 0:
                        //红
                        //int x = 10;
                        //int y = 11;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];
                                //ActChessboard[10 - j, 11 + i].Qizi = (int)QiZiWrite[0];
                                //QiZitoBJ(QiZiWrite);
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (10 - j) * ROWS_AND_COLS + (11 + i) * ROWS + MARKBIT), QiZiWrite, 1, (IntPtr)0);
                                ActChessboard[10 - j, 11 + i].Qizi = BujuInfo[5 * i + j];
                                WritePiece(10 - j, 11 + i, BujuInfo[5 * i + j]);
                            }
                        }
                        break;
                    case 1:
                        //蓝
                        //int x = 11;
                        //int y = 6;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];
                                //ActChessboard[11 + i, 6 + j].Qizi = (int)QiZiWrite[0];
                                //QiZitoBJ(QiZiWrite);
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (11 + i) * ROWS_AND_COLS + (6 + j) * ROWS + MARKBIT), QiZiWrite, 1, (IntPtr)0);
                                ActChessboard[11 + i, 6 + j].Qizi = BujuInfo[5 * i + j];
                                WritePiece(11 + i, 6 + j, BujuInfo[5 * i + j]);
                            }
                        }
                        break;
                    case 2:
                        //绿
                        //int x = 6;
                        //int y = 5;
                        for (int i = 0; i < 6; i++)
                        {
                            for (int j = 0; j < 5; j++)
                            {
                                //QiZiWrite[0] = (uint)BujuInfo[5 * i + j];
                                //ActChessboard[6 + j, 5 - i].Qizi = (int)QiZiWrite[0];
                                //QiZitoBJ(QiZiWrite);
                                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + (6 + j) * ROWS_AND_COLS + (5 - i) * ROWS + MARKBIT), QiZiWrite, 1, (IntPtr)0);
                                ActChessboard[6 + j, 5 - i].Qizi = BujuInfo[5 * i + j];
                                WritePiece(6 + j, 5 - i, BujuInfo[5 * i + j]);
                            }
                        }
                        break;
                }
            }
        }

        /// <summary>
        /// 将棋子转换为标记信息
        /// </summary>
        /// <param name="QiZiRead"></param>
        private void QiZitoBJ(uint[] QiZiRead)
        {
            switch (QiZiRead[0])
            {
                /*军旗：0x00000002→0x13
                  地雷：0x00000003→0xF
                  炸弹：0x00000004→0xB
                  司令：0x00000005→0x8
                  军长：0x00000006→0x9
                  师长：0x00000007→0xA
                  旅长：0X00000008→0xC
                  团长：0X00000009→0xD
                  营长：0X0000000A→0xE
                  连长：0X0000000B→0x10
                  排长：0X0000000C→0x11
                  工兵：0X0000000D→0x12
                  ！ 标记为14→0x01
                  ？ 标记为15→0x02
                  大 标记为16→0x03
                  小 标记为17→0x04
                  第一排 标记为18→0x05
                  中间行 标记为19→0x06
                  后排 标记为1A→0x07
                 */
                case 2:
                    QiZiRead[0] = 0x13;
                    break;
                case 3:
                    QiZiRead[0] = 0xF;
                    break;
                case 4:
                    QiZiRead[0] = 0xB;
                    break;
                case 5:
                    QiZiRead[0] = 8;
                    break;
                case 6:
                    QiZiRead[0] = 9;
                    break;
                case 7:
                    QiZiRead[0] = 0xA;
                    break;
                case 8:
                    QiZiRead[0] = 0xC;
                    break;
                case 9:
                    QiZiRead[0] = 0xD;
                    break;
                case 10:
                    QiZiRead[0] = 0xE;
                    break;
                case 11:
                    QiZiRead[0] = 0x10;
                    break;
                case 12:
                    QiZiRead[0] = 0x11;
                    break;
                case 13:
                    QiZiRead[0] = 0x12;
                    break;
                case 14:
                    QiZiRead[0] = 0x1;
                    break;
                case 15:
                    QiZiRead[0] = 0x2;
                    break;
                case 16:
                    QiZiRead[0] = 0x3;
                    break;
                case 17:
                    QiZiRead[0] = 0x4;
                    break;
                case 18:
                    QiZiRead[0] = 0x5;
                    break;
                case 19:
                    QiZiRead[0] = 0x6;
                    break;
                case 20:
                    QiZiRead[0] = 0x7;
                    break;
            }
        }

        /// <summary>
        /// 从标记转换为棋子
        /// </summary>
        /// <param name="QiZiRead"></param>
        private void BJtoQiZi(uint[] QiZiRead)
        {
            /*军旗：0x00000002←0x13
              地雷：0x00000003←0xF
              炸弹：0x00000004←0xB
              司令：0x00000005←0x8
              军长：0x00000006←0x9
              师长：0x00000007←0xA
              旅长：0X00000008←0xC
              团长：0X00000009←0xD
              营长：0X0000000A←0xE
              连长：0X0000000B←0x10
              排长：0X0000000C←0x11
              工兵：0X0000000D←0x12
              ！ 标记为14←0x01
              ？ 标记为15←0x02
              大 标记为16←0x03
              小 标记为17←0x04
              第一排 标记为18←0x05
              中间行 标记为19←0x06
              后排 标记为1A←0x07
             */
            switch (QiZiRead[0])
            {
                case 0x13:
                    QiZiRead[0] = 2;
                    break;
                case 0xF:
                    QiZiRead[0] = 3;
                    break;
                case 0xB:
                    QiZiRead[0] = 4;
                    break;
                case 8:
                    QiZiRead[0] = 5;
                    break;
                case 9:
                    QiZiRead[0] = 6;
                    break;
                case 0xA:
                    QiZiRead[0] = 7;
                    break;
                case 0xC:
                    QiZiRead[0] = 8;
                    break;
                case 0xD:
                    QiZiRead[0] = 9;
                    break;
                case 0xE:
                    QiZiRead[0] = 10;
                    break;
                case 0x10:
                    QiZiRead[0] = 11;
                    break;
                case 0x11:
                    QiZiRead[0] = 12;
                    break;
                case 0x12:
                    QiZiRead[0] = 13;
                    break;
                case 0x1:
                    QiZiRead[0] = 14;
                    break;
                case 0x2:
                    QiZiRead[0] = 15;
                    break;
                case 0x3:
                    QiZiRead[0] = 16;
                    break;
                case 0x4:
                    QiZiRead[0] = 17;
                    break;
                case 0x5:
                    QiZiRead[0] = 18;
                    break;
                case 0x6:
                    QiZiRead[0] = 19;
                    break;
                case 0x7:
                    QiZiRead[0] = 20;
                    break;

            }
        }

        /// <summary>
        /// 撤消所有标记。
        /// </summary>
        private void BJ_Cls()
        {
            QiZiWrite[0] = 0;
            for (int i = 0; i < 285; i++)
            {
                ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + i * ROWS + MARKBIT), QiZiRead, 1, (IntPtr)0);
                if (QiZiRead[0] != 0 && QiZiRead[0] != 0Xff)
                {
                    ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + i * ROWS + MARKBIT), QiZiWrite, 1, (IntPtr)0);
                }
            }
            step = 0;//步数置0让程序重数初始化数据
            BoardStructure();//清除后重新读入游戏信息
        }

        /// <summary>
        /// 获得四国军棋游戏窗体句柄
        /// </summary>
        private void FindJunQiRpgHwnd()
        {
            //根据窗体标题查找窗口句柄（支持模糊匹配） 
            //Process[] ps = Process.GetProcesses();
            //"四国军旗"在“Windows 任务管理器”中显示为"JunQiRpg.EXE"，但作为
            //GetProcessesByName的参数使用时并不能包含扩展名".EXE"。
            Process[] ps = Process.GetProcessesByName("JunQiRpg");//根据进程名获取进程ID
            IntPtr hwndJunqiRpgtemp = (IntPtr)0;

            //int i = 0;
            foreach (Process p in ps) 
            {
                //if (p.MainWindowTitle.IndexOf("四国军棋角色版") != -1)
                //{
                    hwndJunqiRpgtemp = ProcessApi.OpenProcess(0x1F0FFF, 0, (UInt32)p.Id);  //PROCESS_ALL_ACCESS=0x1F0FFF
                    ProcessApi.ReadProcessMemory(hwndJunqiRpgtemp, MyselfLayoutAddressPointer, QiZiRead, 1, (IntPtr)0);
                    if ((int)QiZiRead[0] != 0)
                    {
                        hwndJunqiRpgOpened = hwndJunqiRpgtemp;
                        //MessageBox.Show(String.Format("第一个子为{0}", QiZiRead[0].ToString()));
                        //wating = false;
                        hwndJunqiRpg = p.MainWindowHandle;
                        JunqiRpgFlag = true;
                        //btn_loginJunQiRpg.Text = "载入四国成功";
                        //btn_loginJunQiRpg.Enabled = false;
                        label3.Text = "四国军棋游戏窗体载入成功";
                        label3.ForeColor = Color.Green;
                        if (chkAutoBJ.Checked == true)
                        {
                            if (Auto == false)//这里判断一下，防止开始标记后，重新初始化
                                Star();
                            else
                                Initializtion();//初始化棋盘
                        }
                        else
                        {
                            Initializtion();//初始化棋盘
                        }

                        
                        ReadMyselfLayoutInfo();//读入自己的布局信息
                    }
                    else
                    {
                        //i++;
                        //MessageBox.Show(String.Format("找到第{0}个复盘", i));
                        ProcessApi.CloseHandle(hwndJunqiRpgtemp);
                    }
                    //return p.MainWindowHandle; 
                //}
                
            } 
        }

        ////打开四国军棋窗体的进程，不能重复调用，二次调用前，必须先关闭hwndJunqiRpgB的进程，
        ////即Gethwnd()与ProcessApi.CloseHandle(hwndJunqiRpgB)需要成对出现。
        //private void Gethwnd()
        //{
        //    //"四国军旗"在“Windows 任务管理器”中显示为"JunQiRpg.EXE"，但作为
        //    //GetProcessesByName的参数使用时并不能包含扩展名".EXE"。
        //    Process[] JunQiRpgProcessID = Process.GetProcessesByName("JunQiRpg"); //根据进程名获取进程ID
        //    IntPtr hwndJunqiRpgB = (IntPtr)0;
        //    ////获取当前进程
        //    //Process current = Process.GetCurrentProcess(); 
        //    ////获取系统所有进程
        //    //Process[] processes = Process.GetProcessesByName (current.ProcessName); 
        //    ////查找相同名称的进程 
        //    if (JunQiRpgProcessID.Length != 0)
        //    {
        //        foreach (Process process in JunQiRpgProcessID)
        //        {
        //            hwndJunqiRpgB = ProcessApi.OpenProcess(0x1F0FFF, 0, (UInt32)process.Id);  //PROCESS_ALL_ACCESS=0x1F0FFF
        //            if (process.MainWindowHandle == hwndJunqiRpg)
        //            {
        //                hwndJunqiRpgOpened = hwndJunqiRpgB;
        //            }
        //            //ProcessApi.CloseHandle(hwndJunqiRpgB);不要关闭。
        //        }
        //    }

        //}

        #region 开始和停止自动标记：Star() 与 Stop()
        private void Star()
        {
            Auto = true;
            //先读取行棋步数
            ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, StepAddressPointet, QiZiRead, 1, (IntPtr)0);
            step = QiZiRead[0];
            Initializtion();
            timer_starBJ.Enabled = true;
            //btn_ZhiNeng.Text = "标记中...";

        }

        private void Stop()
        {
            timer_starBJ.Enabled = false;
            Auto = false;
        }
        #endregion

        //初始化17*17矩阵
        private void Initializtion()
        {
            createIndexFlag = false;
            if (step == 0 && JunqiRpgFlag)//给各方棋子编号及子力初始化
            {
                //红方
                //int x = 10;
                //int y = 11;
                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        ActChessboard[10 - j, 11 + i].Cls();
                        ActChessboard[10 - j, 11 + i].Color = 0;
                        //ActChessboard[10 - j, 11 + i].Num = 5 * i + 4 - j;
                        ActChessboard[10 - j, 11 + i].Num =Convert.ToInt16(5 * i + j);
                    }
                }
                //蓝方
                //int x = 11;
                //int y = 6;
                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        ActChessboard[11 + i, 6 + j].Cls();
                        ActChessboard[11 + i, 6 + j].Color = 1;
                        ActChessboard[11 + i, 6 + j].Num =Convert.ToInt16(5 * i + j);
                    }
                }
                //绿方
                //int x = 6;
                //int y = 5;
                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        ActChessboard[6 + j, 5 - i].Cls();
                        ActChessboard[6 + j, 5 - i].Color = 2;
                        ActChessboard[6 + j, 5 - i].Num = Convert.ToInt16(5 * i + j);
                    }
                }
                //紫方
                //int x = 5;
                //int y = 10;
                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        ActChessboard[5 - i, 10 - j].Cls();
                        ActChessboard[5 - i, 10 - j].Color = 3;
                        ActChessboard[5 - i, 10 - j].Num = Convert.ToInt16(5 * i + j);
                    }
                }
                //中间棋盘
                //x =6;
                //y = 6;
                for (int i = 6; i < 11; i += 2)
                {
                    for (int j = 6; j < 11; j += 2)
                    {
                        ActChessboard[i, j].Cls();
                    }
                }

                //子力初始化
                for (int i = 0; i < 4; i++)
                {
                    piece[i] = 30;
                }

                //最大子力初始化
                for (int i = 0; i < 4; i++)
                {
                    maxpiece[i] = 5;
                }
                createIndexFlag = true;
            }
            else if(JunqiRpgFlag)
            {
                //红方
                //int x = 10;
                //int y = 11;
                for (int i = 6; i < 11; i++)
                {
                    for (int j = 11; j < 17; j++)
                    {
                        ActChessboard[i, j].Cls();
                    }
                }
                //蓝方
                //int x = 11;
                //int y = 6;
                for (int i = 11; i < 17; i++)
                {
                    for (int j = 6; j < 11; j++)
                    {
                        ActChessboard[i,j].Cls();
                    }
                }
                //绿方
                //int x = 6;
                //int y = 5;
                for (int i = 6; i < 11; i++)
                {
                    for (int j = 0; j < 6; j++)
                    {
                        ActChessboard[i,j].Cls();
                    }
                }
                //紫方
                //int x = 5;
                //int y = 10;
                for (int i = 0; i < 6; i++)
                {
                    for (int j = 5; j < 10; j++)
                    {
                        ActChessboard[i, j].Cls();
                    }
                }
                //中间棋盘
                //x =6;
                //y = 6;
                for (int i = 6; i < 11; i += 2)
                {
                    for (int j = 6; j < 11; j += 2)
                    {
                        ActChessboard[i, j].Cls();
                    }
                }
 
            }

            //在游戏检测里有读，这里就不要了。
            //ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, SitColorAddressPointet, QiZiRead, 1, (IntPtr)0);
            //mysitColor = (int)QiZiRead[0];
            BoardStructure();
        }

        /// <summary>
        /// 获取当前游戏信息
        /// </summary>
        private void BoardStructure()
        {
            for (int x = 0; x < 17; x++)
            {
                for (int y = 0; y < 17; y++)
                {
                    if (step != 0)//0步时，直接写
                    {
                        ActChessboard[x, y].Color = ReadColor(x, y);
                    }
                    short qizi = ReadPieceUnmodify(x, y);
                    if (qizi == 1 || qizi==0)//未知时，读标记位
                    {
                        short mark = ReadPiece(x, y);
                        if (mark < 14)
                        {
                            ActChessboard[x, y].Qizi = mark;
                        }
                        else if (mark != 0xFF)
                        {
                            ActChessboard[x, y].Sit = mark;//特殊标记 用于判断座位
                            ActChessboard[x, y].Qizi = 0;
                        }
                        else
                        {
                            ActChessboard[x, y].Qizi = 0;
                        }
                    }
                    else if (qizi != 0xFF)
                    {
                        ActChessboard[x, y].Qizi = qizi;//直接读棋子大小
                    }

                    if (createIndexFlag)
                    {
                        if (step == 0 && ActChessboard[x, y].Color != mysitColor)//对自己不标记(开始前)
                        {
                            //if ((x == 0 || x == 1 || x == 15 || x == 16) || (y == 0 || y == 1 || y == 15 || y == 16))//记录底行棋位
                            if (ActChessboard[x, y].Num >= 20)
                            {
                                if (ActChessboard[x, y].Step > 0)//动过的，至少工兵
                                {
                                    ActChessboard[x, y].Sit = 0xD;//中间行会动，至少工兵
                                    if (ActChessboard[x, y].Qizi == 0)
                                    {
                                        WritePiece(x, y, 20);//最后一排标志
                                    }
                                }
                                else
                                {
                                    ActChessboard[x, y].Sit = 7;//最后两排
                                }
                            }
                            //else if ((x == 5 && y > 5 && y < 11) || (x == 11 && y > 5 && y < 11) || (y == 5 && x > 5 && x < 11) || (y == 11 && x > 5 && x < 11))
                            else if (ActChessboard[x, y].Num >= 0 && ActChessboard[x, y].Num<5)
                            {
                                ActChessboard[x, y].Sit = 5;//第一排
                                if (ActChessboard[x, y].Qizi == 0)
                                {
                                    WritePiece(x, y, 18);
                                }
                            }
                            else
                            {
                                ActChessboard[x, y].Sit = 0xD;//中间行会动，至少工兵
                            }
                        }
                        //else if (step != 0&&(ActChessboard[x, y].Num==26||ActChessboard[x,y].Num==28 )
                        //{
                        //    if(ActChessboard[x, y].Qizi==0
                        //    ActChessboard[x,y].Num==27 ||
                        //    ActChessboard[x,y].Num==29 //(26\28是军旗位)
 
                        //}
                        
                        //清除不正确标记 
                        //第一排不能是 炸弹、地雷、军旗
                        //第二、三、四排不能是 地雷、军旗
                        //第五排不能是 军旗

                        if (ActChessboard[x, y].Num < 5)//第一排
                        {
                            if (ActChessboard[x, y].Qizi == 2 || //旗
                                ActChessboard[x, y].Qizi == 3 ||//雷
                                ActChessboard[x, y].Qizi == 4 //炸
                                )
                            {
                                if (ActChessboard[x, y].Step == 0)//当前字没有走动过
                                {
                                    ActChessboard[x, y].Qizi = 0;
                                    WritePiece(x, y, 15);//标上?号
                                }
                                else
                                {
                                    ActChessboard[x, y].Qizi = 0;
                                    WritePiece(x, y, 14);//标上!号
                                }
                            }
                        }
                        else if (ActChessboard[x, y].Num < 20)//第二、三、四排
                        {
                            if (ActChessboard[x, y].Qizi == 2 || //旗
                                ActChessboard[x, y].Qizi == 3 //雷
                                )
                            {
                                if (ActChessboard[x, y].Step == 0)//当前字没有走动过
                                {
                                    ActChessboard[x, y].Qizi = 0;
                                    WritePiece(x, y, 15);//标上?号
                                }
                                else
                                {
                                    ActChessboard[x, y].Qizi = 0;
                                    WritePiece(x, y, 14);//标上!号
                                }
                            }
                        }
                        else if (ActChessboard[x, y].Num < 26 ||
                            ActChessboard[x,y].Num==27 ||
                            ActChessboard[x,y].Num==29 //(26\28是军旗位)
                            )
                        {
                            if (ActChessboard[x, y].Qizi == 2 //旗
                                )
                            {
                                if (ActChessboard[x, y].Step == 0)//当前字没有走动过
                                {
                                    ActChessboard[x, y].Qizi = 0;
                                    WritePiece(x, y, 15);//标上?号
                                }
                                else
                                {
                                    ActChessboard[x, y].Qizi = 0;
                                    WritePiece(x, y, 14);//标上!号
                                }
                            }
                        }

                    }
                }
            }
        }

        /// <summary>
        /// 自动标记功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_starBJ_Tick(object sender, EventArgs e)
        {
            int movecmd;
            ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, StepAddressPointet, QiZiRead, 1, (IntPtr)0);//读取当前行棋步数
            uint stepTemp = QiZiRead[0];
            if (stepTemp != 0)
            {
                if (step != stepTemp)
                {
                    ////test
                    //textBox1.Text += stepTemp;

                    //判断指令是否执行完毕 为0时表示执行完毕，为1时表示正在执行。
                    ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, InstructionFlagAddressPointer, QiZiRead, 1, (IntPtr)0);
                    uint operastat = QiZiRead[0];
                    if (operastat == 0)
                    {
                        short[] cmd = new short[10];
                        ////test
                        //textBox1.Text = "";
                        for (int i = 0; i < 10; i++)
                        {
                            ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)InstructionAddressPointer + i), QiZiRead, 1, (IntPtr)0);
                            cmd[i] = (short)QiZiRead[0];
                            ////test
                            //textBox1.Text += cmd[i].ToString()+" ";
                        }

                        if (IsCmdChange(cmd))//对比上一次的执行命令
                        {
                            movecmd = cmd[1] % 4;
                            switch (movecmd)
                            {
                                /*军旗：0x00000002
                                  地雷：0x00000003
                                  炸弹：0x00000004
                                  司令：0x00000005
                                  军长：0x00000006
                                  师长：0x00000007
                                  旅长：0X00000008
                                  团长：0X00000009
                                  营长：0X0000000A
                                  连长：0X0000000B
                                  排长：0X0000000C
                                  工兵：0X0000000D
                                 */
                                case 0://移动
                                    MoveChess(cmd);
                                    break;
                                case 1://攻击成功
                                    EatChess(cmd);
                                    break;
                                case 2://攻击失败
                                    LostChess(cmd);
                                    break;
                                case 3://同时阵亡
                                    PerishTogether(cmd);
                                    break;
                            }
                            for (int i = 0; i < 10; i++)//将执行命令储存起来
                            {
                                cmdOperaed[i] = cmd[i];
                            }
                        }
                        //ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, StepAddressPointet, QiZiRead, 1, (IntPtr)0);
                        //step = QiZiRead[0];
                        step = stepTemp;
                        
                        //每移动4步，重新读取标记信息
                        if(step%4==0)
                        {
                            BoardStructure();
                        }
                        //WriteBJtest();
                    }
                }
            }
            else
            {
                if (step != 0)
                {
                    step = 0;
                    SendTime = 0;//下完一局之后，布局发送次数置0，重新发送给对方标记
                    ReSetTime = 0;//记牌重置为０
                    Initializtion();//初始化棋盘
                }
                BoardStructure();
            }

        }

        /// <summary>
        /// 对比两次命令是否一致。
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <returns></returns>
        private bool IsCmdChange(short[] cmd)
        {
            for (int i = 2; i < 6; i++)
            {
                if (cmd[i] != cmdOperaed[i])
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 移动棋子
        /// </summary>
        /// <param name="cmd">移动指令</param>
        private void MoveChess(short[] cmd)
        {
            //ActChessboard[cmd[5], cmd[4]] = ActChessboard[cmd[3], cmd[2]];
            //ActChessboard[cmd[5], cmd[4]].Step++;

            ActChessboard[cmd[5], cmd[4]].Cmd = 0;//这个提前，如果是工兵，Cmd值设置为4，表示棋子值发生了改变
            
            //否则判断是否为工兵
            if (IsOnLoad(cmd))//移动的前后位置都在兵道上
            {
                if (IsSoldier(cmd))//判断为工兵
                {
                    ActChessboard[cmd[5], cmd[4]].Qizi = 0xD;//为工兵
                    ActChessboard[cmd[5], cmd[4]].Cmd = 4;
                }
                else
                {
                    if (ActChessboard[cmd[3], cmd[2]].Qizi != 0 && ActChessboard[cmd[3],cmd[2]].Qizi!=3)//如果已经标记有值，直接复制
                    {
                        ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;
                    }
                    else if(ActChessboard[cmd[3],cmd[2]].Qizi==3)
                    {
                        //错标为雷时
                        ActChessboard[cmd[3], cmd[2]].Qizi = 0;//如果为雷，清0，跟在雷区没标记移动第一步一样
                    }
                }
            }
            else//不在兵道上
            {
                if (ActChessboard[cmd[3], cmd[2]].Qizi != 0 && ActChessboard[cmd[3], cmd[2]].Qizi != 3)//如果已经标记有值，直接复制
                {
                    ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;
                }
                else if(ActChessboard[cmd[3],cmd[2]].Qizi==3)
                {
                    //错标为雷时
                    ActChessboard[cmd[3], cmd[2]].Qizi = 0;//如果为雷，清0，跟在雷区没标记移动第一步一样
                }
            }

            ActChessboard[cmd[5], cmd[4]].Color = ActChessboard[cmd[3], cmd[2]].Color;
            ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
            ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
            ActChessboard[cmd[5], cmd[4]].Step =Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Step + 1);
            ActChessboard[cmd[3], cmd[2]].Cls();
            WriteBJ(cmd);
        }

        /// <summary>
        /// 吃子（攻击成功）
        /// </summary>
        /// <param name="cmd">吃子指令</param>
        private void EatChess(short[] cmd)
        {
            piece[ActChessboard[cmd[5], cmd[4]].Color]--;//被攻击者子力减1
            //先判断攻击者是否为自己
            if (ActChessboard[cmd[3], cmd[2]].Color != mysitColor)//不是
            {
                //判断完被攻击者后还要判断攻击者
                if (ActChessboard[cmd[5], cmd[4]].Qizi != 0 &&
                    ActChessboard[cmd[5], cmd[4]].Qizi != 3 && 
                    ActChessboard[cmd[5], cmd[4]].Qizi != 2 && 
                    ActChessboard[cmd[5], cmd[4]].Qizi != 4 &&//不为炸，如果为炸，则错标，攻击方为未知的情况下至少为排长
                    ActChessboard[cmd[5], cmd[4]].Qizi != 5)//被攻击者有值，且不为地雷、不为司令（司令是不会被吃的！）也不是旗时，取两者中最大值加1级
                {
                    if (ActChessboard[cmd[3], cmd[2]].Qizi - ActChessboard[cmd[5], cmd[4]].Qizi >= 0 || ActChessboard[cmd[3], cmd[2]].Qizi == 0)
                    {
                        ActChessboard[cmd[5], cmd[4]].Qizi -= 1;//比最大值还要大
                        ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
                        ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
                        ActChessboard[cmd[5], cmd[4]].Step =Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Step + 1);
                    }
                    else//攻击者级别本身比被攻击者高
                    {
                        ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;
                        ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
                        ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
                        ActChessboard[cmd[5], cmd[4]].Step =Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Step + 1);
                        //ActChessboard[cmd[5], cmd[4]] = ActChessboard[cmd[3], cmd[2]];
                        //ActChessboard[cmd[5], cmd[4]].Step++;
                    }

                    //还有种工兵挖雷情况
                    if (cmd[4] == 1 || cmd[4] == 15 || cmd[5] == 1 || cmd[5] == 15)//减少运算时间
                    {
                        if (IsOnLoad(cmd))//移动的前后位置都在兵道上
                        {
                            if (IsSoldier(cmd))//判断攻击者为工兵
                            {
                                ActChessboard[cmd[5], cmd[4]].Qizi = 0xD;//为工兵
                                
                            }
                            #region 什么也不做
                            else
                            {
                                //什么也不做
                            }
                        }
                        else
                        {
                            //什么也不做
                        }
                            #endregion
                    }

                    //记牌
                    if (ActChessboard[cmd[5], cmd[4]].Qizi == 0xD)
                    {
                        RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, 3, 2, 0);//挖雷
                    }
                    else
                    {
                        RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 1, -1);
                    }

                    ActChessboard[cmd[5], cmd[4]].Color = ActChessboard[cmd[3], cmd[2]].Color;//记牌后换色

                }
                else if (ActChessboard[cmd[5], cmd[4]].Qizi == 2)//如果是军棋
                {
                    int ClsColor = ActChessboard[cmd[5], cmd[4]].Color;
                    ClsPlayerByColor(ClsColor); //清空当前颜色的所有记录
                    piece[ClsColor] = 0;//子力为0
                    if (ActChessboard[cmd[3], cmd[2]].Qizi == 0)//未知
                    {
                        //默认标记为小
                        ActChessboard[cmd[3], cmd[2]].Sit = 4;
                    }
                    //记牌
                    RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, 2, 2, 0);//被攻击者为全军覆没

                    ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;//当作移动一步
                    ActChessboard[cmd[5], cmd[4]].Color = ActChessboard[cmd[3], cmd[2]].Color;
                    ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
                    ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
                    ActChessboard[cmd[5], cmd[4]].Step =Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Step + 1);
                    
                }
                else if (ActChessboard[cmd[5], cmd[4]].Qizi == 3 || ActChessboard[cmd[5], cmd[4]].Qizi == 5)//当为地雷或者标记为司令时
                {
                    //记牌
                    RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, 3, 2, 0);//挖雷

                    ActChessboard[cmd[5], cmd[4]].Qizi = 0xD;//为工兵
                    ActChessboard[cmd[5], cmd[4]].Color = ActChessboard[cmd[3], cmd[2]].Color;
                    ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
                    ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
                    ActChessboard[cmd[5], cmd[4]].Step =Convert.ToInt16( ActChessboard[cmd[3], cmd[2]].Step + 1);
                    
                }
                else if (ActChessboard[cmd[5], cmd[4]].Qizi == 4)//错标为炸时
                {
                    if (ActChessboard[cmd[3], cmd[2]].Qizi == 0)//攻击者未知
                    {
                        //至少为排长
                        ActChessboard[cmd[3], cmd[2]].Qizi = 0xC;
                    }

                    ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;//当作移动一步

                    //记牌
                    RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 1, -1);

                    ActChessboard[cmd[5], cmd[4]].Color = ActChessboard[cmd[3], cmd[2]].Color;
                    ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
                    ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
                    ActChessboard[cmd[5], cmd[4]].Step = Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Step + 1);

                }
                else//被攻击者的值未知
                {
                    //如果会飞的，那就是工兵了
                    if (IsOnLoad(cmd))//移动的前后位置都在兵道上
                    {
                        if (IsSoldier(cmd))//判断为工兵
                        {
                            ActChessboard[cmd[5], cmd[4]].Qizi = 0xD;//为工兵
                            //记牌
                            RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, 3, 2, 0);//挖雷
                        }
                        else if (ActChessboard[cmd[3], cmd[2]].Qizi == 0)//攻击者的值也未知的时候
                        {
                            ActChessboard[cmd[5], cmd[4]].Qizi = 0xC;//至少排长以上
                            //记牌
                            RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 1, -1);
                        }
                        else
                        {
                            ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;//攻击者取代被攻击者位置
                            //记牌
                            RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 1, -1);
                        }
                    }
                    else if (ActChessboard[cmd[3], cmd[2]].Qizi == 0 ||//攻击者的值也未知的时候
                        ActChessboard[cmd[3], cmd[2]].Qizi == 3 || //如果错标为雷或炸时
                        ActChessboard[cmd[3], cmd[2]].Qizi == 4)
                    {
                        ActChessboard[cmd[5], cmd[4]].Qizi = 0xC;//至少排长以上
                        //记牌
                        RemeberDie(ActChessboard[cmd[5], cmd[4]].Color,12, 1, 1);
                    }
                    else
                    {
                        ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;//攻击者取代被攻击者位置
                        //记牌
                        RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 1, -1);
                    }
                    ActChessboard[cmd[5], cmd[4]].Color = ActChessboard[cmd[3], cmd[2]].Color;
                    ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
                    ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
                    ActChessboard[cmd[5], cmd[4]].Step =Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Step + 1);
                }
                ActChessboard[cmd[5], cmd[4]].Cmd = 1;
                WriteBJ(cmd); //标记
            }
            else//是自己
            {
                //记牌
                if (ActChessboard[cmd[5], cmd[4]].Qizi == 2)//扛旗
                {
                    //记牌
                    RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, 2, 2, 0);//挖雷
                }
                else if (ActChessboard[cmd[3], cmd[2]].Qizi == 0xD)//为兵时
                {
                    //记牌
                    RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, 3, 2, 0);//挖雷
                }
                else if (ActChessboard[cmd[5], cmd[4]].Qizi <= 8 && ActChessboard[cmd[5], cmd[4]].Qizi != 0)
                {
                    RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 2, -1);//旅长以上，不作红标
                }
                else
                {
                    RemeberDie(ActChessboard[cmd[5], cmd[4]].Color, ActChessboard[cmd[3], cmd[2]].Qizi + 1, 1, 2);//作红标并往上溯
                }
                ActChessboard[cmd[5], cmd[4]].Qizi = ActChessboard[cmd[3], cmd[2]].Qizi;//当作移动一步
                ActChessboard[cmd[5], cmd[4]].Color = ActChessboard[cmd[3], cmd[2]].Color;
                ActChessboard[cmd[5], cmd[4]].Sit = ActChessboard[cmd[3], cmd[2]].Sit;
                ActChessboard[cmd[5], cmd[4]].Num = ActChessboard[cmd[3], cmd[2]].Num;
                ActChessboard[cmd[5], cmd[4]].Step =Convert.ToInt16( ActChessboard[cmd[3], cmd[2]].Step + 1);
                
            }
            ActChessboard[cmd[3], cmd[2]].Cls();//清空前一步
        }

        /// <summary>
        /// 攻击失败
        /// </summary>
        /// <param name="cmd">失败指令</param>
        private void LostChess(short[] cmd)
        {
            piece[ActChessboard[cmd[3], cmd[2]].Color]--;//攻击者子力减1

            if (ActChessboard[cmd[5], cmd[4]].Color != mysitColor)//被攻击者不是自己,
            {
                if (IsShowFlag(cmd[1]))//如果降旗
                {
                    ActChessboard[cmd[5], cmd[4]].Qizi = 3;//司令撞死了，为雷
                    //记牌
                    RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, 5, 2, 0);

                    maxpiece[ActChessboard[cmd[3], cmd[2]].Color]++;//最大子力降一级
                    if (ActChessboard[cmd[3], cmd[2]].Color != mysitColor)//攻击者不是自己
                    {
                        ClsCommanderMark(ActChessboard[cmd[3], cmd[2]].Color);//对标识为司令的棋子取消标记
                    }
                }
                else if (ActChessboard[cmd[5], cmd[4]].Num != 26 &&
                    ActChessboard[cmd[5], cmd[4]].Num != 28)//被攻击者不是旗营
                {
                    if (ActChessboard[cmd[3], cmd[2]].Qizi != 0)//攻击者如果有值。
                    {
                        if (ActChessboard[cmd[5], cmd[4]].Qizi == 0 || //被攻击者为空
                            ActChessboard[cmd[5], cmd[4]].Qizi >= ActChessboard[cmd[3], cmd[2]].Qizi || //被攻击者等级低于攻击者
                            ActChessboard[cmd[5], cmd[4]].Qizi == 4)//被攻击者被错标为炸时
                        {
                            ActChessboard[cmd[5], cmd[4]].Qizi = Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Qizi - 1);//被攻击者等级等于攻击者等级加一
                            if (ActChessboard[cmd[5], cmd[4]].Qizi < maxpiece[ActChessboard[cmd[5], cmd[4]].Color] && ActChessboard[cmd[5], cmd[4]].Step == 0)
                            {
                                //比最大子力还大不可能且没有动过，所以为雷
                                ActChessboard[cmd[5], cmd[4]].Qizi = 3;//为雷
                            }
                            else if (ActChessboard[cmd[5], cmd[4]].Qizi < maxpiece[ActChessboard[cmd[5], cmd[4]].Color])
                            {
                                maxpiece[ActChessboard[cmd[5], cmd[4]].Color] = ActChessboard[cmd[5], cmd[4]].Qizi;//把最大值还原
                            }
                        }
                        else if (ActChessboard[cmd[5], cmd[4]].Qizi == 4)
                        {
                            ActChessboard[cmd[5], cmd[4]].Qizi = Convert.ToInt16(ActChessboard[cmd[3], cmd[2]].Qizi - 1);//被攻击者等级等于攻击者等级加一

                        }

                        //记牌
                        if (ActChessboard[cmd[5], cmd[4]].Qizi != 3)//不是碰雷时
                        {
                            RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 1, 2);
                        }
                        else//这里攻击者已经有值
                        {
                            RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 1);
                        }
                        
                    }
                    else
                    {
                        if (ActChessboard[cmd[5], cmd[4]].Qizi == 0)//攻击者无值，被攻击者为空
                        {
                            ActChessboard[cmd[5], cmd[4]].Qizi = 0xC;//至少排长以上
                            //记牌
                            RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, 12, 1, 1);//死了至少为兵，但这里从排长标起。
                        }
                        else//攻击者无值，被攻击者有值
                        {
                            if (ActChessboard[cmd[5], cmd[4]].Qizi == 4)//错标为炸时
                            {
                                ActChessboard[cmd[5], cmd[4]].Qizi = 0xC;//更正为至少排长以上
                                //记牌
                                RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, 12, 1, 1);//死了至少为兵，但这里从排长标起。
                            }
                            else
                            {
                                //记牌
                                RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, ActChessboard[cmd[5], cmd[4]].Qizi + 1, 2, 1);
                            
                            }
                            
                        }
                    }

                    //防止标记出错情况：不管攻击者与被攻击者是否有值如果是出现兵飞雷情况
                    if (IsOnLoad(cmd))
                    {
                        if (IsSoldier(cmd))
                        {
                            if (ActChessboard[cmd[5], cmd[4]].Qizi == 3)//错标为雷时
                            {
                                ActChessboard[cmd[5], cmd[4]].Qizi = 0xC;//更正为至少排长以上
                            }
                        }
                        //记牌
                        RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, 13, 2, 0);//死了兵
                    }
                }
                else//被攻击者是旗营时
                {
                    if(ActChessboard[cmd[3], cmd[2]].Qizi ==0xD)//攻击者是兵时，标为排长
                    {
                        ActChessboard[cmd[5], cmd[4]].Qizi = 0xC;//标为排长
                        //记牌
                        RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, 13, 2, 0);//兵死了

                    }
                    else//攻击者非兵或未知时，标为雷
                    {
                        ActChessboard[cmd[5], cmd[4]].Qizi = 3;//错标为雷时
                        if (ActChessboard[cmd[3], cmd[2]].Qizi != 0)
                        {
                            //记牌
                            RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 0);//
                        }
                        else 
                        {
                            //记牌
                            RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 0);//
                        }
                    }
 
                }

                ActChessboard[cmd[5], cmd[4]].Cmd = 2;
                WriteBJ(cmd);//标记
            }
            else//被攻击者是自己，如果是雷，则检查对方是否为司令
            {
                //检查攻击方的军旗位 如果降旗，对标识为司令的棋子取消标记
                if (ActChessboard[cmd[5], cmd[4]].Qizi == 3)
                {
                    if (IsShowFlag(cmd[1]))
                    {
                        //司令死了,记牌为
                        RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, 5, 2, 0);
                        ClsCommanderMark(ActChessboard[cmd[3], cmd[2]].Color);
                    }
                    else if (ActChessboard[cmd[3], cmd[2]].Qizi != 0)//被攻击者有值
                    {
                        //记牌
                        RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 0);//
                    }
                    else//至少死了个排
                    {
                        //记牌
                        RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, 12, 2, 1);//至少死了个排
                    }
                }
                else
                {
                    //记牌
                    RemeberDie(ActChessboard[cmd[3], cmd[2]].Color, ActChessboard[cmd[5], cmd[4]].Qizi+1, 1, 1);
                }
            }

            ActChessboard[cmd[3], cmd[2]].Cls(); //清空上一步
        }

        /// <summary>
        /// 同归于尽
        /// </summary>
        /// <param name="cmd"></param>
        private void PerishTogether(short[] cmd)
        {
            short color_1 = ActChessboard[cmd[3], cmd[2]].Color;
            short color_2 = ActChessboard[cmd[5], cmd[4]].Color;
            piece[color_1]--;//攻击者子力减1
            piece[color_2]--;//被攻击者子力减1

            //检查双方对应颜色方的军旗位 如果降旗，对双方颜色标识为司令的棋子取消标记
            if (IsShowFlag(cmd[1]))//判断是否降旗
            {
                if (color_1 != mysitColor)//不是自己时才去执行读取及清除
                {
                    if (ReadPieceUnmodify(cmd[7], cmd[6]) == 2)//读取旗位
                    {
                        ActChessboard[cmd[7], cmd[6]].Qizi = 2;
                        //司令死了,记牌为
                        RemeberDie(color_1,5,2,0);
                        ClsCommanderMark(color_1);
                    }
                }
                if (color_2 != mysitColor)//不是自己时才去执行读取及清除
                {
                    if (ReadPieceUnmodify(cmd[9], cmd[8]) == 2)//读取旗位
                    {
                        ActChessboard[cmd[9], cmd[8]].Qizi = 2;
                        //司令死了,记牌为
                        RemeberDie(color_2, 5, 2, 0);
                        ClsCommanderMark(color_2);
                    }
                }
            }
            else if (IsOnLoad(cmd) && IsSoldier(cmd))//判断是否为兵
            {
                RemeberDie(color_1, 13, 2, 1);//攻击者死了兵
                RemeberDie(color_2, 4, 1, 1);//被攻击者死了炸。
            }
            else if (ActChessboard[cmd[3],cmd[2]].Qizi==4)//攻击者为炸
            {
                RemeberDie(color_1, 4, 2, 1);//炸弹
                if (ActChessboard[cmd[5], cmd[4]].Qizi == 0)//被攻击者未知
                {
                    RemeberDie(color_2, 12, 1, 1);//标记为排长
                }
                else
                {
                    RemeberDie(color_2, ActChessboard[cmd[5],cmd[4]].Qizi,1, 1);//标记为排长
                }
            }
            else if (ActChessboard[cmd[5], cmd[4]].Qizi == 4)//被攻击者为炸
            {
                RemeberDie(color_2, 4, 2, 1);//炸弹
                if (ActChessboard[cmd[5], cmd[4]].Qizi == 0)//攻击者未知
                {
                    RemeberDie(color_1, 12, 1, 1);//标记为排长
                }
                else
                {
                    RemeberDie(color_1, ActChessboard[cmd[5], cmd[4]].Qizi, 1, 1);//标记为排长
                }
            }   
            else
            {
                if (ActChessboard[cmd[5], cmd[4]].Qizi == maxpiece[color_1]&&maxpiece[color_1]<7)//被攻击者
                {
                    maxpiece[color_1]++;//最大子力降一级
                }

                if (ActChessboard[cmd[3], cmd[2]].Qizi == maxpiece[color_2] && maxpiece[color_2] < 7)//攻击者
                {
                    maxpiece[color_2]++;//最大子力降一级
                }
                //记牌为
                if (ActChessboard[cmd[5], cmd[4]].Qizi <= ActChessboard[cmd[3], cmd[2]].Qizi && //被攻者大于或者等于攻击者
                    ActChessboard[cmd[5], cmd[4]].Qizi!=0 //被攻击者已知
                    ) //攻击者可能已知或未知
                {
                    RemeberDie(color_1, ActChessboard[cmd[5], cmd[4]].Qizi, 2, 1);//被攻击者最大，以被攻击者为基准
                    RemeberDie(color_2, ActChessboard[cmd[5], cmd[4]].Qizi, 2, 1);
                }
                else if (ActChessboard[cmd[5], cmd[4]].Qizi > ActChessboard[cmd[3], cmd[2]].Qizi && //被攻者小于攻击者
                   ActChessboard[cmd[5], cmd[4]].Qizi != 0 &&//被攻击者已知
                    ActChessboard[cmd[3], cmd[2]].Qizi != 0  //攻击者已知
                   )
                {
                    RemeberDie(color_1, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 1);//攻击者最大，以攻击者为基准
                    RemeberDie(color_2, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 1);
                }
                else if (ActChessboard[cmd[3], cmd[2]].Qizi != 0 && //
                    ActChessboard[cmd[3],cmd[2]].Qizi!=4)//攻击者已知且不为炸
                {
                    RemeberDie(color_1, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 1);//攻击者大
                    RemeberDie(color_2, ActChessboard[cmd[3], cmd[2]].Qizi, 2, 1);
                }
                else
                {
                    RemeberDie(color_1, 12, 1, 1);//排长以上
                    RemeberDie(color_2, 12, 1, 1);//排长以上
                }
            }

            ActChessboard[cmd[5], cmd[4]].Cls();
            ActChessboard[cmd[3], cmd[2]].Cls();
        }



        /// <summary>
        /// 判断某一方是否降旗
        /// </summary>
        /// <param name="cmd_1">指令类型</param>
        /// <returns></returns>
        private bool IsShowFlag(int cmd_1)
        {
            #region 旧处理方法
            //if (maxpiece[color] > 5)
            //{
            //    return false;
            //}
            //else
            //{
            //    int x1, x2, y1, y2;
            //    //读取对应颜色军棋位
            //    switch (color)
            //    {
            //        case 0:
            //            //红方棋位分别为：（7,16）（9,16）
            //            x1 = 7;
            //            y1 = 16;
            //            x2 = 9;
            //            y2 = 16;
            //            if (ReadPieceUnmodify(x1, y1) == 2)
            //            {
            //                maxpiece[0]++;//最大子力降一级
            //                ActChessboard[x1, y1].Qizi = 2;
            //                if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理另一棋位标记数据
            //                {
            //                    WritePiece(x2, y2, 15);
            //                    ActChessboard[x2, y2].Qizi = 0;
            //                }
            //                return true;
            //            }
            //            else
            //            {
            //                if (ReadPieceUnmodify(x2, y2) == 2)
            //                {
            //                    maxpiece[0]++;//最大子力降一级
            //                    ActChessboard[x2, y2].Qizi = 2;
            //                    if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理另一棋位标记数据
            //                    {
            //                        WritePiece(x1, y1, 15);
            //                        ActChessboard[x1, y1].Qizi = 0;
            //                    }
            //                    return true;
            //                }
            //                else
            //                {
            //                    return false;
            //                }
            //            }
            //        case 1:
            //            //蓝方棋位分别为：（16,7）（16,9）
            //            x1 = 16;
            //            y1 = 7;
            //            x2 = 16;
            //            y2 = 9;
            //            if (ReadPieceUnmodify(x1, y1) == 2)
            //            {
            //                maxpiece[1]++;//最大子力降一级
            //                ActChessboard[x1, y1].Qizi = 2;
            //                if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理另一棋位标记数据
            //                {
            //                    WritePiece(x2, y2, 15);
            //                    ActChessboard[x2, y2].Qizi = 0;
            //                }
            //                return true;
            //            }
            //            else
            //            {
            //                if (ReadPieceUnmodify(x2, y2) == 2)
            //                {
            //                    maxpiece[1]++;//最大子力降一级
            //                    ActChessboard[x2, y2].Qizi = 2;
            //                    if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理另一棋位标记数据
            //                    {
            //                        WritePiece(x1, y1, 15);
            //                        ActChessboard[x1, y1].Qizi = 0;
            //                    }
            //                    return true;
            //                }
            //                else
            //                {
            //                    return false;
            //                }
            //            }
            //        case 2:
            //            //绿方棋位分别为：（7,0）（9,0）
            //            x1 = 7;
            //            y1 = 0;
            //            x2 = 9;
            //            y2 = 0;
            //            if (ReadPieceUnmodify(x1, y1) == 2)
            //            {
            //                maxpiece[2]++;//最大子力降一级
            //                ActChessboard[x1, y1].Qizi = 2;
            //                if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理另一棋位标记数据
            //                {
            //                    WritePiece(x2, y2, 15);
            //                    ActChessboard[x2, y2].Qizi = 0;
            //                }
            //                return true;
            //            }
            //            else
            //            {
            //                if (ReadPieceUnmodify(x2, y2) == 2)
            //                {
            //                    maxpiece[2]++;//最大子力降一级
            //                    ActChessboard[x2, y2].Qizi = 2;
            //                    if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理另一棋位标记数据
            //                    {
            //                        WritePiece(x1, y1, 15);
            //                        ActChessboard[x1, y1].Qizi = 0;
            //                    }
            //                    return true;
            //                }
            //                else
            //                {
            //                    return false;
            //                }
            //            }
            //        case 3:
            //            //紫方棋位分别为：（0,7）（0,9）
            //            x1 = 0;
            //            y1 = 7;
            //            x2 = 0;
            //            y2 = 9;
            //            if (ReadPieceUnmodify(x1, y1) == 2)
            //            {
            //                maxpiece[3]++;//最大子力降一级
            //                ActChessboard[x1, y1].Qizi = 2;
            //                if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理另一棋位标记数据
            //                {
            //                    WritePiece(x2, y2, 15);
            //                    ActChessboard[x2, y2].Qizi = 0;
            //                }
            //                return true;
            //            }
            //            else
            //            {
            //                if (ReadPieceUnmodify(x2, y2) == 2)
            //                {
            //                    maxpiece[3]++;//最大子力降一级
            //                    ActChessboard[x2, y2].Qizi = 2;
            //                    if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理另一棋位标记数据
            //                    {
            //                        WritePiece(x1, y1, 15);
            //                        ActChessboard[x1, y1].Qizi = 0;
            //                    }
            //                    return true;
            //                }
            //                else
            //                {
            //                    return false;
            //                }
            //            }
            //        default:
            //            return false;//未知时
            //    }
            //}
            #endregion

            string strcmd = Convert.ToString(cmd_1, 2);//将指令转换为2进制字符串
            if (strcmd.Length < 8)//补0
            {
                string temp="";
                for (int i = 0; i < 8 - strcmd.Length; i++)
                {
                    temp += "0";
                }
                strcmd = temp +strcmd;
            }
            if (strcmd[1] == '1')
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 对标识为司令的棋子取消标记
        /// </summary>
        /// <param name="color">颜色</param>
        private void ClsCommanderMark(int color)
        {
            int i = 0;
            for (int j = 0; j < 17; j++)
            {
                bool outloop = false;
                for (int k = 0; k < 17; k++)
                {
                    if (ActChessboard[j, k].Color == color && ActChessboard[j, k].Qizi == 5)
                    {
                        //WriteBJData((uint)qizi, j, k);//写入标记数据
                        WritePiece(j, k, 15);//重新标上问号
                        i++;
                    }
                    if (i == piece[color])//历遍现有棋子则中断循环
                    {
                        //txtMsg.Text = i.ToString();
                        outloop = true;
                        break;//结束双重循环
                    }
                }
                if (outloop)
                {
                    break;
                }
            }

            if (maxpiece[color] == 5)//最大子力降一级
            {
                maxpiece[color]++;
            }

            ClsFlagMark(color);//对另一旗位处理
        }

        /// <summary>
        /// 清除对应颜色军棋标记
        /// </summary>
        /// <param name="color"></param>
        private void ClsFlagMark(int color)
        {
            int x1, x2, y1, y2;
            //读取对应颜色军棋位
            switch (color)
            {
                case 0:
                    //红方棋位分别为：（7,16）（9,16）
                    x1 = 7;
                    y1 = 16;
                    x2 = 9;
                    y2 = 16;
                    if (ReadPieceUnmodify(x1, y1) == 2)//如果不成立，则另一棋位是真正军旗位
                    {
                        if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理第二旗位标记数据
                        {
                            WritePiece(x2, y2, 15);//标记为问号
                            ActChessboard[x2, y2].Qizi = 0;
                        }
                    }
                    else
                    {
                        if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理第一旗位标记数据
                        {
                            WritePiece(x1, y1, 15);//标记为问号
                            ActChessboard[x1, y1].Qizi = 0;
                        }
                    }
                    break;
                case 1:
                    //蓝方棋位分别为：（16,7）（16,9）
                    x1 = 16;
                    y1 = 7;
                    x2 = 16;
                    y2 = 9;
                    if (ReadPieceUnmodify(x1, y1) == 2)//如果不成立，则另一棋位是真正军旗位
                    {
                        if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理第二旗位标记数据
                        {
                            WritePiece(x2, y2, 15);//标记为问号
                            ActChessboard[x2, y2].Qizi = 0;
                        }
                    }
                    else
                    {
                        if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理第一旗位标记数据
                        {
                            WritePiece(x1, y1, 15);//标记为问号
                            ActChessboard[x1, y1].Qizi = 0;
                        }
                    }
                    break;
                case 2:
                    //绿方棋位分别为：（7,0）（9,0）
                    x1 = 7;
                    y1 = 0;
                    x2 = 9;
                    y2 = 0;
                    if (ReadPieceUnmodify(x1, y1) == 2)//如果不成立，则另一棋位是真正军旗位
                    {
                        if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理第二旗位标记数据
                        {
                            WritePiece(x2, y2, 15);//标记为问号
                            ActChessboard[x2, y2].Qizi = 0;
                        }
                    }
                    else
                    {
                        if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理第一旗位标记数据
                        {
                            WritePiece(x1, y1, 15);//标记为问号
                            ActChessboard[x1, y1].Qizi = 0;
                        }
                    }
                    break;
                case 3:
                    //紫方棋位分别为：（0,7）（0,9）
                    x1 = 0;
                    y1 = 7;
                    x2 = 0;
                    y2 = 9;
                    if (ReadPieceUnmodify(x1, y1) == 2)//如果不成立，则另一棋位是真正军旗位
                    {
                        if (ActChessboard[x2, y2].Color == color && ActChessboard[x2, y2].Qizi == 2) //处理第二旗位标记数据
                        {
                            WritePiece(x2, y2, 15);//标记为问号
                            ActChessboard[x2, y2].Qizi = 0;
                        }
                    }
                    else
                    {
                        if (ActChessboard[x1, y1].Color == color && ActChessboard[x1, y1].Qizi == 2) //处理第一旗位标记数据
                        {
                            WritePiece(x1, y1, 15);//标记为问号
                            ActChessboard[x1, y1].Qizi = 0;
                        }
                    }
                    break;
                default:
                    break;//未知时
            }
        }

        /// <summary>
        /// 判断前后移动位置是否都在兵道上
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private bool IsOnLoad(short[] cmd)
        {
            int x1 = cmd[2];
            int y1 = cmd[3];
            int x2 = cmd[4];
            int y2 = cmd[5];

            if ((x1 == 1 || x1 == 5 || x1 == 11 || x1 == 15) || (y1 == 1 || y1 == 5 || y1 == 11 || y1 == 15) ||
                ((x1 == 6 || x1 == 10) && y1 != 0 && y1 != 16) || ((y1 == 6 || y1 == 10) && x1 != 0 && x1 != 16) || (x1 == 8 && y1 == 8))
            //起始位置在兵道上
            {

                if ((x2 == 1 || x2 == 5 || x2 == 11 || x2 == 15) || (y2 == 1 || y2 == 5 || y2 == 11 || y2 == 15) ||
                ((x2 == 6 || x2 == 10) && y2 != 0 && y2 != 16) || ((y2 == 6 || y2 == 10) && x2 != 0 && x2 != 16) || (x2 == 8 && y2 == 8))
                //移动后的位置在兵道上
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 判断是否为工兵
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private bool IsSoldier(short[] cmd)
        {
            int x1 = cmd[3];
            int y1 = cmd[2];
            int x2 = cmd[5];
            int y2 = cmd[4];

            if (x1 == x2)//X轴上直线
            {
                if (x1 ==7 || x1 ==9)
                {
                    return true;//是兵
                }
                else if (x1 == 8)
                {
                    if (y1 == 1 || y1 == 15 || y2 == 1 || y2 == 15)
                    {
                        return true;//是兵
                    }
                    else//直线，则判断中间是否有阻隔
                    {
                        return LineXPass(x1, ref y1, ref y2);
                    }
                }
                else//直线，则判断中间是否有阻隔
                {
                    return LineXPass(x1, ref y1, ref y2);
                }
            }
            else if (y1 == y2)//Y轴上直线
            {
                if (y1 == 7 || y1 == 9)
                {
                    return true;//是兵
                }
                else if (y1 == 8)
                {
                    if (x1 == 1 || x1 == 15 || x2 == 1 || x2 == 15)
                    {
                        return true;//是兵
                    }
                    else//直线，则判断中间是否有阻隔
                    {
                        return LineYPass(y1, ref x1, ref x2);
                    }
                }
                else//直线，则判断中间是否有阻隔
                {
                    return LineYPass(y1, ref x1, ref x2);
                }
            }
            else if( x1+x2<=11 && ( y1+y2<=11 || ((y1+y2>=21 && y1+y2<=25))))//左边兼上下
            {
                return CurvePass(x1, y1, x2, y2);//通过判断是否可以直接通行从而判断是否为兵
            }
            else if ((x1 + x2 >= 21 && x1 + x2 <= 25) && (y1 + y2 <= 11 || ((y1 + y2 >= 21 && y1 + y2 <= 25))))//右边兼上下
            {
                return CurvePass(x1, y1, x2, y2);//通过判断是否可以直接通行从而判断是否为兵
            }
            else
            {
                return true;//是工兵
            }
        }

        /// <summary>
        /// 直线 X 直接通行
        /// </summary>
        /// <param name="x1">恒定X坐标</param>
        /// <param name="y1">变化Y坐标1</param>
        /// <param name="y2">变化Y坐标2</param>
        /// <returns>是兵则返回真</returns>
        private bool LineXPass(int x1, ref int y1, ref int y2)
        {
            int temp;
            if (y1 > y2)
            {
                temp = y1;
                y1 = y2;
                y2 = temp;
            }

            for (int i = y1 + 1; i < y2; i++)
            {
                if (ActChessboard[x1, i].Color != -1 && ActChessboard[x1, i].Color != 0xff)
                {
                    //中间有阻隔,是兵
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 直线 Y 直接通行
        /// </summary>
        /// <param name="y1">恒定X坐标</param>
        /// <param name="x1">变化Y坐标1</param>
        /// <param name="x2">变化Y坐标2</param>
        /// <returns>是兵则返回真</returns>
        private bool LineYPass(int y1, ref int x1, ref int x2)
        {
            int temp;
            if (x1 > x2)
            {
                temp = x1;
                x1 = x2;
                x2 = temp;
            }

            for (int i = x1 + 1; i < x2; i++)
            {
                if (ActChessboard[i, y1].Color != -1 && ActChessboard[i, y1].Color != 0xff)
                {
                    //中间有阻隔,是兵
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 曲线直接通行
        /// </summary>
        /// <param name="x1">起始X坐标</param>
        /// <param name="y1">起始Y坐标</param>
        /// <param name="x2">终止X坐标</param>
        /// <param name="y2">终止Y坐标</param>
        /// <returns>是兵则返回真</returns>
        private bool CurvePass(int x1, int y1, int x2, int y2)
        {
            int X = x1 + x2;
            int Y = y1 + y2;
            if (X < 12)//左
            {
                if (Y < 12)//左下(6,6)
                {
                    return (LineXPass(6, ref y1, ref y2) || LineYPass(6, ref x1, ref x2));//先x轴不变,再y轴不变
                }
                else//左上(6,10)
                {
                    return (LineXPass(6, ref y1, ref y2) || LineYPass(10, ref x1, ref x2));//先x轴不变,再y轴不变
                }
            }
            else//右
            {
                if (Y < 12)//右下(10,6)
                {
                    return (LineXPass(10, ref y1, ref y2) || LineYPass(6, ref x1, ref x2));//先x轴不变,再y轴不变
                }
                else//右上(10,10)
                {
                    return (LineXPass(10, ref y1, ref y2) || LineYPass(10, ref x1, ref x2));//先x轴不变,再y轴不变
                }
            }
        }

        /// <summary>
        /// 根据颜色清空玩家所有信息
        /// </summary>
        /// <param name="ClsColor"></param>
        private void ClsPlayerByColor(int ClsColor)
        {
            piece[ClsColor]=0;//子力置0
            for (int i = 0; i < 17; i++)
            {
                for (int j = 0; j < 17; j++)
                {
                    if (ActChessboard[i, j].Color == ClsColor)
                    {
                        ActChessboard[i, j].Cls();
                    }
                }
            }
        }

        /// <summary>
        /// 根据指令中移动后的位置坐标进行标记。（用于指令执行后）
        /// </summary>
        /// <param name="cmd"></param>
        private void WriteBJ(short[] cmd)
        {
            /*标记信息如下
             * ！ 标记为01
             * ？ 标记为02
             * 大 标记为03
             * 小 标记为04
             * 一排 标记为05
             * 第中间行 标记为06
             * 后排 标记为07 
             */
            //uint[] A;
            if (ActChessboard[cmd[5], cmd[4]].Cmd == 0 )//移动
            {
                if (ActChessboard[cmd[5], cmd[4]].Sit == 7 && ActChessboard[cmd[5], cmd[4]].Step == 1 && ActChessboard[cmd[5], cmd[4]].Qizi == 0)
                {
                    //A = new uint[] { (uint)ActChessboard[cmd[5], cmd[4]].Sit };//标记位置信息
                    //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + cmd[4] * ROWS + cmd[5] * ROWS_AND_COLS + MARKBIT), A, 1, (IntPtr)0);
                    WritePiece(cmd[5], cmd[4],ActChessboard[cmd[5], cmd[4]].Sit,true);//标记位置信息
                    ActChessboard[cmd[5], cmd[4]].Sit = 0xD;//会动的，最小工兵
                }
            }
            else if (ActChessboard[cmd[5], cmd[4]].Sit <= 4 && ActChessboard[cmd[5], cmd[4]].Sit > 0 && ActChessboard[cmd[5], cmd[4]].Cmd == 1)
                //用未知的子扛旗时，读取特殊标记位Sit 默认：Sit==4 即：小
            {
                //A = new uint[] { (uint)ActChessboard[cmd[5], cmd[4]].Sit };
                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + cmd[4] * ROWS + cmd[5] * ROWS_AND_COLS + MARKBIT), A, 1, (IntPtr)0);
                WritePiece(cmd[5], cmd[4], ActChessboard[cmd[5], cmd[4]].Sit,true);
            }
            else if (ActChessboard[cmd[5], cmd[4]].Cmd != -1 && ActChessboard[cmd[4],cmd[5]].Cmd!=3) //攻击或吃子或变化
            {
                //A = new uint[] { (uint)ActChessboard[cmd[5], cmd[4]].Qizi };
                //QiZitoBJ(A);
                //ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + cmd[4] * ROWS + cmd[5] * ROWS_AND_COLS + MARKBIT), A, 1, (IntPtr)0);
                WritePiece(cmd[5], cmd[4], ActChessboard[cmd[5], cmd[4]].Qizi);
            }
            ActChessboard[cmd[5], cmd[4]].Cmd = -1;//标记完成后，设置为初始值-1；
            #region 分布要注释的。
            //WriteBJtest();
            #endregion
        }

        /// <summary>
        /// 测试自动标记时，用于将棋子信息显示于文本框，发布程序时，应该去除
        /// </summary>
        private void WriteBJtest()
        {
            textBox1.Text = "";
            //for (int i = 0; i < 17; i++)
            //{
            //    for (int j = 0; j < 17; j++)
            //    {
            //        textBox1.Text += String.Format("{0}",ActChessboard[i, j].Qizi);
            //    }
            //    textBox1.Text += "\n";
            //}
            for (int j = 0; j <16; j++)
            {
                for (int i = 0; i <16; i++)
                {
                    textBox1.Text += ActChessboard[i,j].Color.ToString();
                }
                textBox1.Text += " \n";
            }
        }

        /// <summary>
        /// 程序初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mainfrm_Load(object sender, EventArgs e)
        {
            Instance.TopMost = true;//窗体置于顶层
            Instance.MaximizeBox = false;//去掉最大化按钮
            Instance.Opacity = 1;//窗口透明度
            //this.MaximizedBounds.Height = 292;
            //Instance.MaximizedBounds.Width = 197;
            //Instance.MaximumSize.Width = 197;
            //Instance.MaximumSize.Height = 292;

            textBox1.ScrollBars = ScrollBars.Both;

            btn_Ok.Enabled = false;
            btn_Cancel.Enabled = false;
            btn_Open.Enabled = false;

            tabControl1.TabPages[0].Text = "标记";
            tabControl1.TabPages[1].Text = "联机";

            chkAutoBJ.CheckState = CheckState.Checked;


            //联机模块初始化
            AcceptButton = btnSend;
            btnCloseSer.Enabled = false;
            btnSend.Enabled = false;

            txtIP.Text = "127.0.0.1";//"5.147.13.42";
            txtPort.Text = "1001";
            btnConnect.Enabled = false;

            cmbVersion.SelectedIndex=3;

            //记牌功能模块初始化
           
            //添加新的 TabPage
            TabPage tp = new TabPage("记牌");
            new TabControl.TabPageCollection(tabControl1).Add(tp);
            //自定义控件
            monitorCtrl = new MonitorCtrl();

            // 设置monitorCtrl的停靠
            monitorCtrl.Dock = System.Windows.Forms.DockStyle.Fill;

            // 将自定义控件添加到选项页
            tp.Controls.Add(monitorCtrl);


            #region 发布要写上的。
            textBox1.Visible = false;
            checkBox1.Enabled = false;
            #endregion
        }

        /// <summary>
        /// 获取程序的编译时间
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        DateTime GetPe32Time(string fileName)
        {
            int seconds;
            using (BinaryReader br = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read)))
            {
                byte[] bs = br.ReadBytes(2);
                if (bs.Length != 2) return DateTime.MinValue;
                if (bs[0] != 'M' || bs[1] != 'Z') return DateTime.MinValue;
                br.BaseStream.Seek(0x3c, SeekOrigin.Begin);
                byte offset = br.ReadByte();
                br.BaseStream.Seek(offset, SeekOrigin.Begin);
                bs = br.ReadBytes(4);
                if (bs.Length != 4) return DateTime.MinValue;
                if (bs[0] != 'P' || bs[1] != 'E' || bs[2] != 0 || bs[3] != 0) return DateTime.MinValue;
                bs = br.ReadBytes(4);
                if (bs.Length != 4) return DateTime.MinValue;
                seconds = br.ReadInt32();
            }
            return DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc).
                    AddSeconds(seconds).ToLocalTime();
        }

        /// <summary>
        /// 托盘图标单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (WindowState == FormWindowState.Minimized)
                {
                    Visible = true;
                    WindowState = FormWindowState.Normal;
                    ShowInTaskbar = true;
                }
                else
                {
                    WindowState = FormWindowState.Minimized;
                    Visible = false;
                }
            }
        }

        /// <summary>
        /// 窗体状态发生改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mainfrm_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                ShowInTaskbar = true;
            }
        }

        /// <summary>
        /// 读取棋子颜色信息
        /// </summary>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <returns>返回颜色值</returns>
        private short ReadColor(int x, int y)
        {
            ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + x * ROWS_AND_COLS + y * ROWS  + COLORBIT), QiZiRead, 1, (IntPtr)0);//读取颜色信息
            short color = (short)QiZiRead[0];
            return color;
        }

        /// <summary>
        /// 读取棋子标记信息
        /// </summary>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <returns>返回标记大小</returns>
        private short ReadPiece(int x, int y)
        {
            ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + x * ROWS_AND_COLS + y * ROWS  + MARKBIT), QiZiRead, 1, (IntPtr)0);
            BJtoQiZi(QiZiRead);
            short piecedata = (short)QiZiRead[0];
            return piecedata;
        }

        /// <summary>
        /// 读取棋子真实大小
        /// </summary>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <returns>返回棋子真实大小</returns>
        private short ReadPieceUnmodify(int x, int y)
        {
            ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + x * ROWS_AND_COLS + y * ROWS  + UNMODIFYBIT), QiZiRead, 1, (IntPtr)0);
            short piecedata = (short)QiZiRead[0];
            return piecedata;
        }

        /// <summary>
        /// 写入棋子信息
        /// </summary>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <param name="qizi">棋子大小</param>
        private void WritePiece(int x, int y, int qizi)
        {
            QiZiWrite[0] = (uint)qizi;
            QiZitoBJ(QiZiWrite);
            ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + x * ROWS_AND_COLS + y * ROWS  + MARKBIT), QiZiWrite, 1, (IntPtr)0);
        }

        /// <summary>
        /// 写入棋子信息
        /// </summary>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <param name="bj">标记大小</param>
        /// <param name="isBj">是否为标记</param>
        private void WritePiece(int x, int y, int bj, bool isBj)
        {
            if (isBj)
            {
                QiZiWrite[0] = (uint)bj;
                ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + x * ROWS_AND_COLS + y * ROWS + MARKBIT), QiZiWrite, 1, (IntPtr)0);
            }
        }

        /// <summary>
        /// 写入翻牌标记数据
        /// </summary>
        /// <param name="qizi">棋子大小</param>
        /// <param name="x">坐标X</param>
        /// <param name="y">坐标Y</param>
        private void WritePieceUnmodify(int x, int y, short qizi)
        {
            QiZiWrite[0] = (uint)qizi;
            ProcessApi.WriteProcessMemory(hwndJunqiRpgOpened, (IntPtr)((int)JunQiRpgAddressPointer + x * ROWS_AND_COLS + y * ROWS  + UNMODIFYBIT), QiZiWrite, 1, (IntPtr)0);
        }

        #endregion

        #region 联机功能区
        //*************************联机功能 网络连接，数据传输
		//服务端专有变量===
		private Socket mySocket;
        private Thread serverThread; //启动服务线程
        private TcpListener myListener;
		//===end
		
		//客户端专有变量===
		private Thread clientThread; //启动服务线程
		private TcpClient tcpclient;
		//===end
		
		//公共变量===
        private string ServerType = "Server";
		private Thread recvThread;  //接收信息线程
        private StreamReader streamReader;
        private StreamWriter streamWriter;
        private NetworkStream networkStream;
        private int item = 0;//消息框消息条数（第一条为0）
        bool Connected = false;//联机连接状态
		//===end
        
        //*************************

        #region 服务端专有方法
        /// <summary>
        /// 更新服务端IP
        /// </summary>
        private void IPcnn()
        {
            //获得IP
            //修改Ini，上传
            AddItem("正在获取外网IP...");
            Server ip = new Server();
            string S_IP = ip.GetIP();
            if (S_IP != "失败！")
            {
                try
                {
                    AddItem("外网IP为" + S_IP);
                    txtIP.Text = S_IP;
                    AddItem("正在更新IP信息...");
                    NetApi.WritePrivateProfileString("ServerIP", "IP", S_IP, Application.StartupPath + "\\IPinfo");
                    NetApi.WritePrivateProfileString("ServerIP", "Port", txtPort.Text, Application.StartupPath + "\\IPinfo");
                    ip.UploadFileByFtp("ftp://174.128.236.188/", "25410", "1350926487", "IPinfo", "/info/game/junqi/ServerIP.html");
                    AddItem("更新IP地址为" + S_IP);
                    AddItem("更新端口号为" + txtPort.Text);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    AddItem(e.Message);
                }
            }
        }
		
		/// <summary>
        /// 侦听端口，等待客户端接连
        /// </summary>
        private void Lisent()
        {
            try
            {
                IPAddress ipa;
                int S_port = Convert.ToInt32(txtPort.Text);
                if (txtIP.Text != "")

                {
                    ipa = IPAddress.Parse(txtIP.Text);//换成自动
                }
                else
                {
                    IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());//自动获取
                    ipa = ipe.AddressList[0];
                    AddText(ipa.ToString());
                }
                myListener = new TcpListener(ipa, S_port);
                myListener.Start();
                AddItem("服务已经启动");
                AddItem("正在等待客户端接入");
                SerStarConfigControl();

                bool hadCnn = false;
                while (!hadCnn)
                {
                    if (myListener != null && myListener.Pending())
                    {
                        mySocket = myListener.AcceptSocket();//同步
                        hadCnn = true;
                    }
                    Thread.Sleep(100);
                }

                CliArriveConfigControl();
                AddItem("客户端成功连接上服务器");
                networkStream = new NetworkStream(mySocket);
                streamReader = new StreamReader(networkStream);
                streamWriter = new StreamWriter(networkStream);
                recvThread = new Thread(new ThreadStart(RecvData));
                recvThread.IsBackground = true;//后台线程
                recvThread.Start();
                Connected = true;
            }
            catch (Exception e)
            {
                if (e.Message == "正在中止线程。")
                {
                    return;
                }
                MessageBox.Show(e.Message + e.GetBaseException(), "Server提示");

            }
        
        }



        delegate void AddTextDelegate(string str);

        private void AddText(string str)
        {
            if (this.txtIP.InvokeRequired)//等待异步
            {
                AddItemDelegate addtext = new AddItemDelegate(AddText);
                this.Invoke(addtext, str);//通过代理调用刷新方法
            }
            else
            {
                txtIP.Text = str;
            }
        }
#endregion

        #region 客户端专有方法
        /// <summary>
        /// 连接服务端
        /// </summary>
        private void Connection()
        {
            try
            {
                tcpclient = new TcpClient();
                tcpclient.Connect(txtIP.Text, Convert.ToInt32(txtPort.Text));
            }
            catch (Exception)
            {
                MessageBox.Show("没有连接到服务器", "Client提示");
                CliFailConfigControl();
                return;
            }

            AddItem("成功连接上服务器");
            Connected = true;
            CnnSerConfigControl();
            //timer4_netMark.Enabled = true;
            networkStream = tcpclient.GetStream();
            streamReader = new StreamReader(networkStream);
            streamWriter = new StreamWriter(networkStream);
            //sendThread = new Thread(new ThreadStart(SendData));//发送线程要放到接收线程之前
            //sendThread.IsBackground = true;
            recvThread = new Thread(new ThreadStart(RecvData));
            recvThread.IsBackground = true;
            recvThread.Start();
        }

#endregion

        #region 公共方法
        /// <summary>
        /// 向客户端发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (txtMsg.Text == "")
            {
                MessageBox.Show("发送信息不能为空", "提示");
            }
            else
            {
                //sendThread = new Thread(new ThreadStart(SendData));
                //sendThread.IsBackground = true;
                //sendThread.Start();
                SendData(txtMsg.Text);
                ClsMsg();
            }
            
        }
		
		//服务端：启动连网，更新服务端外网IP及端口数据
		//客户端：获取服务端IP及端口
		
		private void btnConnect_Click(object sender, EventArgs e)
        {
            if (ServerType == "Server")
			{
				IPcnn();
			}else
			{
				//btnCnn.Enabled = true;
                btnStartSer.Enabled = true;
				btnSend.Enabled = false;
				btnPickup.Enabled = false;
				//btnStop.Enabled = false;
                btnCloseSer.Enabled = false;
				Client ipinfo = new Client();
				try
				{
					ipinfo.DownLoadIPinfo();
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
				finally
				{
					txtIP.Text = ipinfo.GetIP();
					txtPort.Text = ipinfo.GetPort();
				}
			}
        }
		
		/// <summary>
        /// 启动服务器或连接客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartSer_Click(object sender, EventArgs e)
        {
            chkServerType.Enabled = false;
			if(ServerType =="Server")
			{
				serverThread = new Thread(new ThreadStart(Lisent));
				serverThread.IsBackground = true;//后台
				serverThread.Start();
			}else
			{
				clientThread = new Thread(new ThreadStart(Connection));
				clientThread.IsBackground = true;
				clientThread.Start();
			}
        }
		
		/// <summary>
        /// 停止服务器 或客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCloseSer_Click(object sender, EventArgs e)
        {
            chkServerType.Enabled = true;
            try
            {
                if (btnSend.Enabled == true)
                {
                    SendData("exit");
                    //streamWriter.Flush();
                }
                else if(ServerType =="Server")//服务器端要多处理这部分
                {
                    CloseConfigControl();
                    AddItem("服务器关闭");
                    //				recvThread.Abort();
                    myListener.Stop();
                    serverThread.Abort();
                }

            }
            catch (Exception)
            {
            }
            finally 
            {
            }
        }
		
		//发送数据
        private void SendData(string str)
        {
			try
			{
				if (str != "exit")

				{
					AddItem("向对家发送:" + str);
					//mySocket.Send(Encoding.Unicode.GetBytes(txtMsg.Text));
					streamWriter.WriteLine(str);
					streamWriter.Flush();
				}
				else
				{
					if(ServerType =="Server")
					{
						streamWriter.WriteLine(str);
						streamWriter.Flush();
						CloseConfigControl();
						AddItem("发送连接请求...");
					}else
					{
						AddItem("发送连接请求...");
						streamWriter.WriteLine(str);
						streamWriter.Flush();
						AddItem("客户端关闭");
						CloseConfigControl();
                        ReleaseResource();
					}
					//ReleaseResource();
				}
			}
			catch (Exception e)
            {
                MessageBox.Show(e.Message, "发送出错");
            }
        }
		
		/// <summary> 
        /// 定义接收数据代理 
        /// </summary> 
        private delegate void RecvDataDelegate();

        //接收数据
        private void RecvData()
        {
            try
            {
                string msg = streamReader.ReadLine();
                while (!msg.Equals("exit"))
                {
                    string tempstr = msg.Substring(0,1);
                    if (tempstr!="A"&&tempstr!="B"&&tempstr!="C")
                    {
                        AddItem("来自对家:" + msg);
                        tabpageOpera(1);//自动跳转
                    }
                    else
                    {
                        AddItem("来自对家新的布局信息");
                        MarkMsg = msg;
                        ArriveFlag = true;
                    }
                    msg = streamReader.ReadLine();
                    
                }
				if(!(ServerType =="Server"))
				{
					SendData("exit");
				}
            }
            catch (Exception)
            {

            }
            finally
            {
				if(ServerType =="Server")
				{
					AddItem("客户已经关闭");
					AddItem("服务器关闭");
				}else
				{
					//收到服务器退出的消息，释放资源
					AddItem("服务器关闭");
					AddItem("连接断开");
				}
                CloseConfigControl();
                Connected = false;
                ReleaseResource();
                //服务端接收数据 //客户端错误处理
            }
            //};

            //streamReader.Close();
            //streamWriter.Close();
            //networkStream.Close();
            //mySocket.Shutdown(SocketShutdown.Both);//无法访问已经释放对象
            //mySocket.Close();
            //BtnCloseSerClick(this,null);
        }
		
		delegate void ClsMsgDelegate();

        private void ClsMsg()
        {
            if (txtMsg.InvokeRequired)
            {
                ClsMsgDelegate clsmsgDelegate = new ClsMsgDelegate(ClsMsg);
                this.Invoke(clsmsgDelegate, null);
            }
            else
            {
                txtMsg.Text = "";
            }
        }
		
		delegate void ConfigControlDelegate();

        /// <summary>
        /// 服务器启动按钮控件设置
        /// </summary>
        private void SerStarConfigControl()
        {
            if (btnStartSer.InvokeRequired)
            {
                ConfigControlDelegate config = new ConfigControlDelegate(SerStarConfigControl);
                this.Invoke(config);
            }
            else
            {
                btnStartSer.Enabled = false;
                btnCloseSer.Enabled = true;
                btnSend.Enabled = false;
                //btnPickup.Enabled = false;
            }
        }
        
        /// <summary>
        /// 客户端连接上按钮控件设置
        /// </summary>
        private void CliArriveConfigControl()
        {
            if (btnSend.InvokeRequired)
            {
                ConfigControlDelegate config = new ConfigControlDelegate(CliArriveConfigControl);
                this.Invoke(config);
            }
            else
            {
                btnSend.Enabled = true;
                //btnPickup.Enabled = true;
            }
        }

        /// <summary>
        /// 客户端连接失败按钮控件设置
        /// </summary>
        private void CliFailConfigControl()
        {
            if (btnSend.InvokeRequired)
            {
                ConfigControlDelegate config = new ConfigControlDelegate(CliFailConfigControl);
                this.Invoke(config);
            }
            else
            {
                //btnSend.Enabled = true;
                //btnPickup.Enabled = true;
                chkServerType.Enabled = true;
            }
        }
		
		/// <summary>
        /// 连接上服务端按钮控件设置
        /// </summary>
        private void CnnSerConfigControl()
        {
            if (btnStartSer.InvokeRequired)
            {
                ConfigControlDelegate config = new ConfigControlDelegate(CnnSerConfigControl);
                this.Invoke(config);
            }
            else
            {
                btnStartSer.Enabled = false;
                btnSend.Enabled = true;
                btnPickup.Enabled = true;
                //btnStop.Enabled = true;
                btnCloseSer.Enabled = true;
            }
        }

        /// <summary>
        /// 服务端或客户端关闭，又或者连接丢失按键控件设置
        /// </summary>
        private void CloseConfigControl()
        {
            if (btnSend.InvokeRequired)
            {
                ConfigControlDelegate config = new ConfigControlDelegate(CloseConfigControl);
                this.Invoke(config);
            }
            else
            {
				btnSend.Enabled = false;
				btnCloseSer.Enabled = false;
				btnStartSer.Enabled = true;
				//btnPickup.Enabled = false;
            }
        }
        
        delegate void tabpageOperaDelegate(int i);
        /// <summary>
        /// 联机或标记页面显示
        /// </summary>
        /// <param name="i">index i</param>
        private void tabpageOpera(int i)
        {
            if (this.tabControl1.InvokeRequired)//等待异步
            {
                tabpageOperaDelegate tabpageopera = new tabpageOperaDelegate(tabpageOpera);
                this.Invoke(tabpageopera, i);//通过代理调用刷新方法
            }
            else
            {
                tabControl1.SelectedIndex = i;
            }
        }
		
		/// <summary>
        /// 提取布局
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPickup_Click(object sender, EventArgs e)
        {
            //if (Connected && JunqiRpgFlag)
            //{
            //    SendBujuInfo(buju[5]); 
            //}
            if (txtMsg.Text.Length > 32)
            {
                ArriveConvertBuJuInfo(txtMsg.Text);
                AddItem("标记成功");
            }
        }

		delegate void AddItemDelegate(string str);//定义委托
        private void AddItem(string str)
        {
            if (this.listBox1.InvokeRequired)//等待异步
            {
                AddItemDelegate additem = new AddItemDelegate(AddItem);
                this.Invoke(additem, str);//通过代理调用刷新方法
            }
            else
            {
                listBox1.Items.Add(str);
                item = listBox1.Items.Count - 1;
                listBox1.SetSelected(item, true);
            }
        }
		
		/// <summary>
        /// 释放资源
        /// </summary>
        private void ReleaseResource()
        {
			if(ServerType =="Server")
			{
				recvThread.Abort();
				streamReader.Close();
				streamWriter.Close();
				networkStream.Close();
				mySocket.Shutdown(SocketShutdown.Both);//无法访问已经释放对象

				mySocket.Disconnect(true);//关闭套接字并允许重用
				mySocket.Close();
				myListener.AcceptSocket().Disconnect(true);//关闭套接字并允许重用
				myListener.AcceptSocket().Close();
				myListener.Stop();//未连接时中断会抛出异常，mySocket = myListener.AcceptSocket();这句在活动
				//myListener.Server.Disconnect(true);
				//serverThread.Abort();
				Connected = false;
				//timer4_netMark.Enabled = false;
				//serverThread.Abort();
			}else
			{
				recvThread.Abort();//此线程要提到networkStream.Close()之前；
				if (networkStream != null)
				{
					streamReader.Close();
					streamWriter.Close();
					networkStream.Close();
				}
				//sendThread.Abort();
				clientThread.Abort();
				tcpclient.Close();
				Connected = false;
				}
        }
        #endregion

        private void chkServerType_CheckedChanged(object sender, EventArgs e)
        {
            if (chkServerType.Checked == true)
            {
                ServerType = "Client";
                btnStartSer.Text = "连接";
                btnCloseSer.Text = "断开";
            }
            else
            {
                ServerType = "Server";
                btnStartSer.Text = "启动";
                btnCloseSer.Text = "停止";
            }

            AssemblyName aName = this.GetType().Assembly.GetName();
            Version v = aName.Version;
            //int rev = Convert.ToInt32(svnid.Split(' ')[1]);
            DateTime CompileTime = GetPe32Time(this.GetType().Assembly.Location);
            VERSION = Text = string.Format("四国双人行({2}) {0} [{1} 测试版本](511576392@qq.com)", v, CompileTime.ToString("yyyy-MM-dd"),ServerType);
            Instance.Text = VERSION;
            notifyIcon1.Text = VERSION;
        }
        #endregion

        #region 标记及联机综合区

        private bool ArriveFlag = false;//当有信息到达，未进行标记时为true;
        private bool MyselfLayoutChangeFlag = true;//自己的布局或位置变化时为true
        private string MarkMsg;
        private int SendTime = 0;

        /// <summary>
        /// 将布局转换成字符串信息
        /// </summary>
        /// <param name="BujuInfo">布局信息</param>
        /// <returns>布局字符串信息</returns>
        private string ConvertBuJuToStr(string Flag, int color, short[] BujuInfo)
        {
            string str = "";
            str += Flag;
            str += color.ToString();
            for (int i = 0; i < 30; i++)
            {
                str += BujuInfo[i].ToString() + " ";
            }
            //追求卓越，成功会不经意间追上你。
            return str;
        }

        /// <summary>
        /// 将字符串信息转换布局
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>返回布局数组</returns>
        private short[] ConvertStrToBuJu(string str)
        {
            short[] bujuInfo = new short[30];
            string temp = str.Substring(2, str.Length - 2);
            string[] strBujuinfo = temp.Split(' ');
            for (int i = 0; i < 30; i++)
            {
                bujuInfo[i] = Convert.ToInt16(strBujuinfo[i]);

            }
            return bujuInfo;
        }

        /// <summary>
        /// 保存服务端或客户端传来的布局信息
        /// </summary>
        /// <param name="msg">到达的消息</param>
        private void ArriveConvertBuJuInfo(string msg)
        {
            try
            {
                string msgflag = msg.Substring(0, 1);
                switch (msgflag)
                {
                    case "A":
                        break;
                    case "B":
                        buju[6].Color = Convert.ToInt16(msg.Substring(1, 1));
                        buju[6].BuJuInfo = ConvertStrToBuJu(msg);
                        if (JunqiRpgFlag)//确定游戏已经启动
                        {
                            if (step == 0)
                            {
                                BJ_buju(false, buju[6].Color, buju[6].BuJuInfo);
                            }
                            else
                            {
                                StarMark(false, buju[6].Color, buju[6].BuJuInfo);
                            }//StarMark(buju[6].Color, buju[6].BuJuInfo); 
                        }
                        break;
                    case "C":
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                txtMsg.Text=e.Message;
            }
        }

        /// <summary>
        /// 给服务端或客户端发送布局信息
        /// </summary>
        /// <param name="buju">BJInfo类实例</param>
        private void SendBujuInfo(BJInfo markbuju)
        {
            string strFlag = "B";
            int color = markbuju.Color;

            string strBuju = ConvertBuJuToStr(strFlag, color, markbuju.BuJuInfo);

            if (Connected)//判断连接是否存在
            {
                SendData(strBuju);//发送数据
            }
        }

        /// <summary>
        /// 根据布局信息对某一方进行标记
        /// </summary>
        /// <param name="type">标记类型：以标记写入为false,以翻牌写入为true</param>
        /// <param name="color">要标记的颜色</param>
        /// <param name="arrBuju">布局</param>
        private void StarMark(bool type,int color, short[] arrBuju)
        {
            int num;
            int i = 0;
            short qizi;

            if (createIndexFlag)
            {
                if (type == false)
                {
                    for (int j = 0; j < 17; j++)
                    {
                        bool outloop = false;
                        for (int k = 0; k < 17; k++)
                        {
                            if (ActChessboard[j, k].Color == color)
                            {
                                num = ActChessboard[j, k].Num;
                                qizi = arrBuju[num];
                                ActChessboard[j, k].Qizi = qizi;
                                WritePiece(j, k,qizi);//写入标记数据
                                i++;
                            }
                            if (i == piece[color])//历遍现有棋子则中断循环
                            {
                                //txtMsg.Text = i.ToString();
                                outloop = true;
                                break;//结束双重循环
                            }
                        }
                        if (outloop)
                        {
                            break;
                        }
                    }
                }
                else//翻牌标记
                {
                    for (int j = 0; j < 17; j++)
                    {
                        bool outloop = false;
                        for (int k = 0; k < 17; k++)
                        {
                            if (ActChessboard[j, k].Color == color)
                            {
                                num = ActChessboard[j, k].Num;
                                qizi = arrBuju[num];
                                ActChessboard[j, k].Qizi = qizi;
                                WritePieceUnmodify(j, k,qizi);//写入标记数据
                                i++;
                            }
                            if (i == 30)
                            {
                                outloop = true;
                                break;//结束双重循环
                            }
                        }
                        if (outloop)
                        {
                            break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 提取红色标记信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPickUpRed_Click(object sender, EventArgs e)
        {
            PickUpChessInfoByColor(0);
        }

        /// <summary>
        /// 提取绿色标记信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPickUpGreen_Click(object sender, EventArgs e)
        {
            PickUpChessInfoByColor(2);
        }

        /// <summary>
        /// 提取蓝色标记信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPickUpBlue_Click(object sender, EventArgs e)
        {
            PickUpChessInfoByColor(1);
        }

        /// <summary>
        /// 提取紫色标记信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPickUpPurple_Click(object sender, EventArgs e)
        {
            PickUpChessInfoByColor(3);
        }

        /// <summary>
        /// 根据颜色信息提取对应布局
        /// </summary>
        /// <param name="color"></param>
        private void PickUpChessInfoByColor(int color) 
        {
            BJInfo pickupbuju = new BJInfo();
            string strFlag = "B";
            string strBuju = "";

            pickupbuju.BuJuInfo = new short[30];
            for(int i=0;i<30;i++)
            {
                pickupbuju.BuJuInfo[i]=0;
            }

            if (createIndexFlag)
            {
                int index = 0;
                for (int x = 0; x < 17; x++)
                {
                    bool outloop = false;
                    for (int y = 0; y < 17; y++)
                    {
                        if (ActChessboard[x, y].Color == color)
                        {
                            pickupbuju.BuJuInfo[ActChessboard[x, y].Num] = ActChessboard[x, y].Qizi;
                            index++;
                        }
                        if (index == piece[color])//历遍现有棋子则中断循环
                        {
                            outloop = true;
                            break;//结束双重循环
                        }

                    }
                    if (outloop)
                    {
                        break;
                    }
                }
                strBuju = ConvertBuJuToStr(strFlag, color, pickupbuju.BuJuInfo);
            }
            else
            {
                strBuju = "无法提取对应颜色布局";
            }
            txtMsg.Text = strBuju;
        }
        #endregion

        #region 记牌功能区
        public static int[,] record = new int[4, 25]{
            { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},//红、
            { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},//蓝、
            { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},//绿、
            { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}//紫
        };

        MonitorCtrl monitorCtrl;
        private int ReSetTime = 0;

        /// <summary>
        /// 记牌
        /// </summary>
        /// <param name="color">玩家棋子颜色</param>
        /// <param name="qizi">棋子大小</param>
        /// <param name="dieMode">死亡状态：1对掉（相对的），2被吃（绝对的），0正常</param>
        /// <param name="upordown">0为等大，1向上溯（已知最小值），-1向下溯，2向上溯（已知最大值）</param>
        private void RemeberDie(int color, int qizi, int dieMode, int upordown)
        {
            int layout = QiziToLayout(qizi);
            int[] index = LayoutToIndex(layout);
            //int[] arr = new int[25];
            //for (int i = 0; i < 25; i++)
            //{
            //    arr[i]=record[color, i];
            //}
            if (color != -1)
            {

                switch (upordown)
                {
                    case 0://等大
                        for (int i = 0; i < index[1]; i++)
                        {
                            if (dieMode != record[color, index[0] + i])
                            {
                                record[color, index[0] + i] = dieMode;
                                monitorCtrl.AtuoFillColor(color, index[0] + i);
                                break;
                            }
                        }
                        break;
                    case 1://大于或等于，向上溯(知道最小值)
                        for (int i = index[0] + index[1] - 1; i >= 0; i--)
                        {
                            if (dieMode != record[color, i])
                            {
                                record[color, i] = dieMode;
                                monitorCtrl.AtuoFillColor(color, i);
                                break;
                            }
                        }

                        break;
                    case -1://小于或等于，向下溯(知道最大值)
                        for (int i = 0; i < 16; i++)
                        {
                            if (dieMode != record[color, index[0] + i])
                            {
                                record[color, index[0] + i] = dieMode;
                                monitorCtrl.AtuoFillColor(color, index[0] + i);
                                break;
                            }
                        }
                        break;
                    case 2://小于或等于，向上溯(知道最大值)
                        for (int i = 15; i > index[0] + index[1] - 1; i--)
                        {
                            if (dieMode != record[color,i])
                            {
                                record[color, i] = dieMode;
                                monitorCtrl.AtuoFillColor(color, i);
                                break;
                            }
                        }
                        break;
                }
            }

            //monitorCtrl.Refresh();
        }

        private int QiziToLayout(int qizi)
        {
            /*11军旗：0x00000002→24
             10 地雷：0x00000003→21-23
             9 炸弹：0x00000004→19、20
             0 司令：0x00000005→0
             1 军长：0x00000006→1
             2 师长：0x00000007→2、3
             3 旅长：0X00000008→4、5
             4 团长：0X00000009→6、7
             5 营长：0X0000000A→8、9
             6 连长：0X0000000B→10-12
             7 排长：0X0000000C→13-15
             8 工兵：0X0000000D→16-18
             */

            //棋子转为Index
            int layout;
            switch (qizi)
            {
                case 2:
                    layout = 11;
                    break;
                case 3:
                    layout = 10;
                    break;
                case 4:
                    layout = 9;
                    break;
                case 5:
                    layout = 0;
                    break;
                case 6:
                    layout = 1;
                    break;
                case 7:
                    layout = 2;
                    break;
                case 8:
                    layout = 3;
                    break;
                case 9:
                    layout = 4;
                    break;
                case 10:
                    layout = 5;
                    break;
                case 11:
                    layout = 6;
                    break;
                case 12:
                    layout = 7;
                    break;
                case 13:
                default :
                    layout = 8;
                    break;
            }
            return layout;
        }

        private int[] LayoutToIndex(int layout)
        {
             /*11军旗：0x00000002→24
             10 地雷：0x00000003→21-23
             9 炸弹：0x00000004→19、20
             0 司令：0x00000005→0
             1 军长：0x00000006→1
             2 师长：0x00000007→2、3
             3 旅长：0X00000008→4、5
             4 团长：0X00000009→6、7
             5 营长：0X0000000A→8、9
             6 连长：0X0000000B→10-12
             7 排长：0X0000000C→13-15
             8 工兵：0X0000000D→16-18
             */
            int[] index= new int[2];//第一为起始索引，第二为长度
            switch (layout)
            {
                case 0:
                    index[0] = 0;//起始索引
                    index[1] = 1;//长度
                    break;
                case 1:
                    index[0] = 1;//起始索引
                    index[1] = 1;//长度
                    break;
                case 2:
                    index[0] = 2;//起始索引
                    index[1] = 2;//长度
                    break;
                case 3:
                    index[0] = 4;//起始索引
                    index[1] = 2;//长度
                    break;
                case 4:
                    index[0] = 6;//起始索引
                    index[1] = 2;//长度
                    break;
                case 5:
                    index[0] = 8;//起始索引
                    index[1] = 2;//长度
                    break;
                case 6:
                    index[0] = 10;//起始索引
                    index[1] = 3;//长度
                    break;
                case 7:
                    index[0] = 13;//起始索引
                    index[1] = 3;//长度
                    break;
                case 8:
                    index[0] = 16;//起始索引
                    index[1] = 3;//长度
                    break;
                case 9:
                    index[0] = 19;//起始索引
                    index[1] = 3;//长度
                    break;
                case 10:
                    index[0] = 21;//起始索引
                    index[1] = 3;//长度
                    break;
                case 11:
                    index[0] = 24;//起始索引
                    index[1] = 1;//长度
                    break;
            }
            return index;
        }
        #endregion


        #region 热键注册、注销
        /// <summary>
        /// 热键注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mainfrm_Activated(object sender, EventArgs e)
        {
            ////注册热键Shift+S，Id号为100。HotKey.KeyModifiers.Shift也可以直接使用数字4来表示。
            //HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Shift, Keys.S);
            ////注册热键Ctrl+B，Id号为101。HotKey.KeyModifiers.Ctrl也可以直接使用数字2来表示。
            //HotKey.RegisterHotKey(Handle, 101, HotKey.KeyModifiers.Ctrl, Keys.B);
            //注册热键Alt+1，Id号为100。HotKey.KeyModifiers.Alt也可以直接使用数字1来表示。
            HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Alt, Keys.D1);
            //注册热键Alt+2，Id号为101。HotKey.KeyModifiers.Alt也可以直接使用数字1来表示。
            HotKey.RegisterHotKey(Handle, 101, HotKey.KeyModifiers.Alt, Keys.D2);
            //注册热键Alt+3，Id号为102。HotKey.KeyModifiers.Alt也可以直接使用数字1来表示。
            HotKey.RegisterHotKey(Handle, 102, HotKey.KeyModifiers.Alt, Keys.D3);
            //注册热键Alt+4，Id号为103。HotKey.KeyModifiers.Alt也可以直接使用数字1来表示。
            HotKey.RegisterHotKey(Handle, 103, HotKey.KeyModifiers.Alt, Keys.D4);
            //注册热键Alt+5，Id号为104。HotKey.KeyModifiers.Alt也可以直接使用数字1来表示。
            HotKey.RegisterHotKey(Handle, 104, HotKey.KeyModifiers.Alt, Keys.D5);

        }

        /// <summary>
        /// 热键注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mainfrm_Leave(object sender, EventArgs e)
        {
            //注销Id号为100的热键设定
            HotKey.UnregisterHotKey(Handle, 100);
            //注销Id号为101的热键设定
            HotKey.UnregisterHotKey(Handle, 101);
            //注销Id号为102的热键设定
            HotKey.UnregisterHotKey(Handle, 102);
            //注销Id号为103的热键设定
            HotKey.UnregisterHotKey(Handle, 103);
            //注销Id号为104的热键设定
            HotKey.UnregisterHotKey(Handle, 104);
        }
        #endregion

        #region 实现热键响应
        /// 
        /// 监视Windows消息
        /// 重载WndProc方法，用于实现热键响应
        /// 
        /// 
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            char ch='n';
            //按快捷键 
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100:    //按下的是Alt+1
                            //Button btn = new Button();
                            //btn.Click += new EventHandle(btn_Ok_Click);
                            //Trigger(btn,EventArgs.Empty);//相当于鼠标点击触发
                            ch = 'l';
                            //btn_Ok_Click(new object(),EventArgs.Empty);
                            break;
                        case 101:    //按下的是Alt+2
                            //ReadyGo();//游戏开始
                            ch = 'u';
                            break;
                        case 102:    //按下的是Alt+3
                            ch='r';
                            break;
                        case 103://按下的是Alt+4
                            ch = 'd';
                            break;
                        case 104://按下的是Alt+3
                            ch = 'm';
                            break;
                    }
                    break;
            }
            if (ch!='n')
            {
                HotkeyMarker(ch);
            }
            base.WndProc(ref m);
        }

        private void HotkeyMarker(char ch)
        {
            bool StartFlag=false;//游戏是否开始
            if (BeginAddressPointer != (IntPtr)0x0)
            {
                ProcessApi.ReadProcessMemory(hwndJunqiRpgOpened, BeginAddressPointer, QiZiRead, 1, (IntPtr)0);//读取开始按钮是否存在，不存在则已经准备，不能对自己调入布局
                uint beginBtn = QiZiRead[0];
                if(beginBtn==0)//不存在
                {
                    StartFlag = true;//游戏已经开始
                }
            }
            switch (ch)
            {
                case 'l':
                    if (btn_Left.Enabled == true)
                    {
                        btn_Left_Click(btn_Left, EventArgs.Empty);
                    }
                    //if(rd_btns[1].Enabled==true).Checked = true;
                    break;
                case 'u':
                    if (btn_Up.Enabled == true)
                    {
                        btn_Up_Click(btn_Up, EventArgs.Empty);
                    }
                    break;
                case 'r':
                    if (btn_Right.Enabled == true)
                    {
                        btn_Right_Click(btn_Right, EventArgs.Empty);
                    }
                    break;
                case 'm':
                    if (btnMySelf.Enabled == true)
                    {
                        btnMySelf_Click(btnMySelf, EventArgs.Empty);
                        if (rd_btns[0].Enabled == true)//有调入布局的情况选已经调入的布局
                        {
                            rd_btns[0].Checked = true;

                        }
                        else //否则选复盘
                        {
                            playerFlag = mysitColor;
                            SelectBJ();
                        }

                    }
                    break;
                case 'd':
                    playerFlag=mysitColor;
                    //label3.Text = "将对 自己　调入布局……";
                    SelectBJ();
                    
                    btn_Ok.Enabled = true;
                    btn_Cancel.Enabled = true;
                    break;
            }

            if (step == 0 && !StartFlag)
            {
                playerFlag = -1;
            }
            //if (btn_Ok.Enabled == true && ch != 'd')
            //{
            //    btn_Ok_Click(btn_Ok, EventArgs.Empty);
            //}
            //else if (btn_Ok.Enabled == true && ch=='d' && )
            //{
            //    MessageBox.Show("行棋过程中不能对自己进行标记");
            //}
            if ((step != 0 || StartFlag) && (playerFlag == mysitColor || playerFlag==-1))
            {
                MessageBox.Show("行棋过程中不能对自己进行标记");
            }
            else
            {
                btn_Ok_Click(btn_Ok, EventArgs.Empty);
            }

        }

        #endregion
    }
}